Dzyann
Dzyann

Reputation: 5208

Is there a way to know of what type is the property bound to my DependencyProperty?

I would like to know what is the Type that is bound to the DependencyProperty of my control. Is there a way to know that?

I have a DependencyProperty like this:

public static readonly DependencyProperty MyValueProperty =
        DependencyProperty.Register("MyValue", typeof(double?), typeof(MyControl),
                                    new FrameworkPropertyMetadata
                                        {
                                            BindsTwoWayByDefault = true,
                                            DefaultUpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged,
                                            PropertyChangedCallback = OnMyValueChanged
                                        });

    public double? MyValue
    {
        get { return (double?)GetValue(MyValueProperty); }
        set { SetValue(MyValueProperty, value); }
    }

This is a property of my control, and people can use it like:

<myNamespace:MyControl MyValue="{Binding THEIRProperty}"/>

THEIRProperty can be anything, I would like to know the actual type of THEIRProperty inside my control, is this possible?

I tried checking on the BindingOperations, but I couldn't find anything. I would like to know, for example if they are binding a double or a double?.

Upvotes: 0

Views: 115

Answers (1)

Rohit Vats
Rohit Vats

Reputation: 81253

There is no publicly exposed property on BindingExpression which can get you source type but it is stored in private field i.e. _sourceType which you can get via reflection:

private static void OnMyValueChanged(DependencyObject d, 
                                     DependencyPropertyChangedEventArgs args)
{
   var bindingExpression = BindingOperations.GetBindingExpression(d, 
                                             MyControl.MyValueProperty);
   Type sourceType = (Type)bindingExpression.GetType()
                         .GetField("_sourceType", BindingFlags.NonPublic | 
                             BindingFlags.Instance).GetValue(bindingExpression);
   bool isNullableDouble = sourceType == typeof(double?);
   bool isDouble = sourceType == typeof(double);
}

Also it is stored in private getter property ConverterSourceType which can also be used to get the source type:

Type sourceType = (Type)bindingExpression.GetType()
                  .GetProperty("ConverterSourceType", BindingFlags.Instance |
                              BindingFlags.NonPublic).GetGetMethod(true)
                             .Invoke(bindingExpression, null);

Upvotes: 1

Related Questions