As you can see from the error , you can only bind to the dependency property . But since it already inherits from the DataTemplateSelector , you cannot inherit the DependencyObject class.
So, I would suggest creating an Attached property for the binding purpose. But the catch property is bound only to the class derived from DependencyObject.
So, you need a little tweak to make it work for you. Let me explain step by step.
First one . Create an 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 one . As I said, it can only be set for an object originating from DependencyObject, so set it to 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 the template from the container object passed as a parameter. Get Parent (ContentControl) using VisualTreeHelper and get the value of the 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);
You can also get a ContentControl as follows (container as FrameworkElement).TemplatedParent .
Rohit vats
source share