【问题标题】:Is there a way to know of what type is the property bound to my DependencyProperty?有没有办法知道绑定到我的 DependencyProperty 的属性是什么类型?
【发布时间】:2014-02-01 01:31:56
【问题描述】:

我想知道绑定到我的控件的 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?

【问题讨论】:

  • 当 THEIRProperty 类型不是 double 类型时,您没有收到绑定错误吗?还是双倍?为什么你想知道这个?
  • @blindmeis,不,您不会收到错误消息。事实上,您可以绑定一个布尔值并且它可以工作。我想知道,因为如果他们绑定双精度,我想添加验证以使输入成为必需。
  • @Dzyann 如果您正在开发一个UserControl 供其他人使用,那么您有责任验证用户尝试绑定到您的属性的内容...如果他们绑定一个无效的类型,它不会起作用,这将是他们的问题,而不是你的。
  • @Sheridan,控件是为支持双精度而构建的,现在急于需要让它支持双精度?还。我不想把使用它的项目弄乱吗?因此,如果我可以添加一个验证器,他们的应用程序仍然可以像以前一样工作。
  • @RohitVats,我在 View 中使用它进行测试,似乎那里有一些错误,导致它弄乱了绑定。我修改了所有的绑定,它开始工作了。

标签: wpf xaml binding


【解决方案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);

【讨论】:

  • 这行得通,尽管“_sourceType”会引发异常,因为该属性实际上来自基类。我使用了“ConverterSourceType”。
猜你喜欢
  • 1970-01-01
  • 2013-08-08
  • 2012-02-27
  • 1970-01-01
  • 2011-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-12
相关资源
最近更新 更多