Bind a property to DataTemplateSelector

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.

Leave a Comment