Bind a property to DataTemplateSelector

后端 未结 1 675
闹比i
闹比i 2020-12-03 15:33

I want to design a DataTemplateSelector who compare the given value with a one passed in parameter and choose the right template if the value is superior or inferior

相关标签:
1条回答
  • 2020-12-03 16:35

    As evident from the error you can only bind with dependency property. But since it's already inheriting from DataTemplateSelector, you cannot inherit from DependencyObject class.

    So, I would suggest to create an Attached property for binding purpose. But catch is attached property can only be applied on class deriving from DependencyObject.

    So, you need to tweak a bit to get it working for you. Let me explain step by step.


    First - Create attached property as suggested above:

    public class DataTemplateParameters : DependencyObject
    {
        public static double GetValueToCompare(DependencyObject obj)
        {
            return (double)obj.GetValue(ValueToCompareProperty);
        }
    
        public static void SetValueToCompare(DependencyObject obj, double value)
        {
            obj.SetValue(ValueToCompareProperty, value);
        }
    
        public static readonly DependencyProperty ValueToCompareProperty =
            DependencyProperty.RegisterAttached("ValueToCompare", typeof(double),
                                                  typeof(DataTemplateParameters));
    
    }
    

    Second - Like I said it can be set only on object deriving from DependencyObject, so set it on ContentControl:

    <ContentControl Grid.Row="2" Content="{Binding Path=PropertyName}"
              local:DataTemplateParameters.ValueToCompare="{Binding DecimalValue}">
       <ContentControl.ContentTemplateSelector>
          <local:InferiorSuperiorTemplateSelector
               SuperiorTemplate="{StaticResource SuperiorTemplate}"
               InferiorTemplate="{StaticResource InferiorTemplate}" />
       </ContentControl.ContentTemplateSelector>
    </ContentControl>
    

    Third. - Now you can get the value inside template from container object passed as parameter. Get Parent (ContentControl) using VisualTreeHelper and get value of attached property from it.

    public override System.Windows.DataTemplate SelectTemplate(object item, 
                                          System.Windows.DependencyObject container)
    {
       double dpoint = Convert.ToDouble(item);
       double valueToCompare = (double)VisualTreeHelper.GetParent(container)
                 .GetValue(DataTemplateParameters.ValueToCompareProperty); // HERE
       // double valueToCompare = (container as FrameworkElement).TemplatedParent; 
       return (dpoint >= valueToCompare) ? SuperiorTemplate : InferiorTemplate;
    }
    

    Also you can get ContentControl like this (container as FrameworkElement).TemplatedParent.

    0 讨论(0)
提交回复
热议问题