Using binding for the Value property of DataTrigger condition

后端 未结 4 576
无人及你
无人及你 2020-11-29 07:55

I\'m working on a WPF application and struggling with a data trigger. I\'d like to bind the value of the trigger condition to some object I have:



        
4条回答
  •  -上瘾入骨i
    2020-11-29 08:57

    The Value property of the DataTrigger is not a DependencyProperty that can be bind. Therefore, we RegisterAttached a dependency property that can bind and set the value of DataTrigger's Value property each time the attached dependency property value is set.

    Here is an example DataTriggerAssists class

    public class DataTriggerAssists
    {
        public static readonly DependencyProperty ValueProperty =
            DependencyProperty.RegisterAttached(
                "Value",
                typeof(object),
                typeof(DataTriggerAssists),
                new FrameworkPropertyMetadata(null, OnValueChanged));
    
        public static object GetValue(DependencyObject d)
        {
            return d.GetValue(ValueProperty);
        }
    
        public static void SetValue(DependencyObject d, object value)
        {
            d.SetValue(ValueProperty, value);
        }
    
        public static void OnValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs args)
        {
            if (d is DataTrigger trigger)
                trigger.Value = args.NewValue;
        }
    }
    

    Declare a prefix named as with the namespace of the DataTriggerAssists class.

    Then you can use like this.

    ..
    

提交回复
热议问题