Wpf 有没有办法知道该属性绑定到我的DependencyProperty的类型?
我想知道绑定到控件DependencyProperty的类型是什么。有办法知道吗 我有一个类似这样的财产:Wpf 有没有办法知道该属性绑定到我的DependencyProperty的类型?,wpf,xaml,binding,Wpf,Xaml,Binding,我想知道绑定到控件DependencyProperty的类型是什么。有办法知道吗 我有一个类似这样的财产: public static readonly DependencyProperty MyValueProperty = DependencyProperty.Register("MyValue", typeof(double?), typeof(MyControl), new FrameworkProp
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}"/>
他们的财产可以是任何东西,我想知道我控制的财产的实际类型,这可能吗
我试图检查BindingOperations,但什么也找不到。我想知道,例如,他们是绑定一个双精度还是一个双精度在
BindingExpression
上没有公开的属性可以获取源类型,但它存储在私有字段中,即\u 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);
当它们的属性类型为另一个double时,您没有得到绑定错误吗?还是双份?你为什么想知道这些?@blindmeis,不,你没有错。事实上,你可以绑定一个布尔值,它可以工作。我想知道,因为如果他们绑定了一个double,我想添加一个验证,以使输入成为必需的。@Dzyann如果您正在开发一个供他人使用的
UserControl
,验证用户试图绑定到您的属性的内容不是您的责任。。。如果他们绑定了一个无效的类型,它将无法工作,这将是他们的问题,而不是你的问题。@Sheridan,该控件是为了支持double而构建的,现在我需要让它支持double?也。我不想把使用它的项目搞得一团糟?因此,如果我可以添加一个验证器,他们的应用程序将仍然像以前一样工作。@RohitVats,我在测试视图中使用它,似乎那里有一些错误,导致绑定混乱。我修改了所有的绑定,它开始工作了。虽然“\u sourceType”抛出了一个异常,但这是有效的,因为该属性实际上来自基类。我使用了“ConverterSourceType”。