Binding the Path Property of a Binding

前端 未结 5 1788
广开言路
广开言路 2020-12-11 09:24

is it possible to bind the Path property of a binding to another property?

I want to realize this code:

Text=\"{Binding Path={Binding Path=CurrentPat         


        
5条回答
  •  一生所求
    2020-12-11 09:58

    I worked it out on myself.

    Heres the solution, I hope it might help anyone got the same problem like me.

    public class CustomBindingBehavior : Behavior
    {
        public bool IsBinding
        {
            get
            {
                return (bool)GetValue(IsBindingProperty);
    
            }
            set
            {
                SetValue(IsBindingProperty, value);
            }
        }
    
        public string PropertyPath
        {
            get
            {
                return (string)GetValue(PropertyPathProperty);
    
            }
            set
            {
                SetValue(PropertyPathProperty, value);
            }
        }
    
        public static DependencyProperty
            PropertyPathProperty = DependencyProperty.Register("PropertyPath", typeof(string),
                            typeof(CustomBindingBehavior), null);
    
        public static DependencyProperty
            IsBindingProperty = DependencyProperty.Register("IsBinding", typeof(bool),
                            typeof(CustomBindingBehavior), null);
    
        protected override void OnAttached()
        {
            if (AssociatedObject is TextBlock)
            {
                var tb = AssociatedObject as TextBlock;
                tb.Loaded += new RoutedEventHandler(tb_Loaded);
            }
        }
    
        private void tb_Loaded(object sender, RoutedEventArgs e)
        {
            AddBinding(sender as TextBlock, TextBlock.TextProperty);
        }
    
        private void AddBinding(DependencyObject targetObj, DependencyProperty targetProp)
        {
            if (IsBinding)
            {
                Binding binding = new Binding();
                binding.Path = new PropertyPath(this.PropertyPath, null);
    
                BindingOperations.SetBinding(targetObj, targetProp, binding);
            }
            else
            {
                targetObj.SetValue(targetProp, this.PropertyPath);
            }
        }
    }
    

    And heres the implementation in XAML:

    
                    
                        
                    
                
    

    Greetings Jonny

提交回复
热议问题