我想知道绑定到我的控件的DependencyProperty的Type是什么。有没有办法知道这个?
我有一个像这样的DependencyProperty:
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); }
}
这是我控制的属性,人们可以像以下一样使用它:
<myNamespace:MyControl MyValue="{Binding THEIRProperty}"/>
THEIRProperty可以是任何东西,我想知道我控制范围内THEIRProperty的实际类型,这可能吗?
我试过检查BindingOperations,但我找不到任何东西。我想知道,例如,如果他们绑定了 double 或 double?。
答案 0 :(得分:1)
BindingExpression
上没有公开曝光的属性可以获取源类型,但它存储在私有字段中,即_sourceType
,您可以通过反射获取:
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);
}
它也存储在私有getter属性ConverterSourceType
中,也可用于获取源类型:
Type sourceType = (Type)bindingExpression.GetType()
.GetProperty("ConverterSourceType", BindingFlags.Instance |
BindingFlags.NonPublic).GetGetMethod(true)
.Invoke(bindingExpression, null);