2013-04-29 28 views
1

如何获取绑定属性的底层数据类型?获取绑定的底层数据类型

出于测试目的,我创建了一个视图模型'Person',它具有Int32类型的'Age'属性,该属性绑定到文本框的文本属性。

有什么样...

BindingOperations.GetBindingExpression(this, TextBox.TextProperty).PropertyType 

或将这些信息只能通过反射进行检索?

myBinding.Source.GetType().GetProperty("Age").PropertyType 

编辑: 我有一个自定义文本框类,在这里我想给自己带上validationrules,转换器......

这将是巨大进去F.E.信息文本框类的'load'事件。

回答

0

你可以得到的值转换器的转换方法中:

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { 
    value.GetType();/*The bound object is here 
} 

XAML

Text="{Binding Age, Mode=TwoWay,Converter={StaticResource converterName}}" 

不知道你在哪里需要访问的类型,但它是在这个水平,如果你需要改变价值。

+0

是的,但我不能在这里使用它。 我想附上一个数字验证规则,检查底层类型的最小值和最大值。 – user2332314 2013-04-30 04:47:53

0

如果属性绑定到你需要在文本框中的值设置为属性的有效值前,将更新视图模型源

看来,任何验证错误停止视图特定的数据类型模型更新。我认为这是垃圾。

0

我发现要做到这一点的唯一方法就是使用反射。以下代码获取绑定的对象。它还处理嵌套绑定{Binding Parent.Value},如果存在转换器 - 它会返回转换后的值。该方法还返回该项目为null的案例的类型。

private static object GetBindedItem(FrameworkElement fe, out Type bindedItemType) 
    { 
     bindedItemType = null; 
     var exp = fe.GetBindingExpression(TextBox.TextProperty); 

     if (exp == null || exp.ParentBinding == null || exp.ParentBinding.Path == null 
      || exp.ParentBinding.Path.Path == null) 
      return null; 

     string bindingPath = exp.ParentBinding.Path.Path; 
     string[] elements = bindingPath.Split('.'); 
     var item = GetItem(fe.DataContext, elements, out bindedItemType); 

     // If a converter is used - don't ignore it 
     if (exp.ParentBinding.Converter != null) 
     { 
      var convOutput = exp.ParentBinding.Converter.Convert(item, 
       bindedItemType, exp.ParentBinding.ConverterParameter, CultureInfo.CurrentCulture); 
      if (convOutput != null) 
      { 
       item = convOutput; 
       bindedItemType = convOutput.GetType(); 
      } 
     } 
     return item; 
    } 

    private static object GetItem(object data, string[] elements, out Type itemType) 
    { 
     if (elements.Length == 0) 
     { 
      itemType = data.GetType(); 
      return data; 
     } 
     if (elements.Length == 1) 
     { 
      var accesor = data.GetType().GetProperty(elements[0]); 
      itemType = accesor.PropertyType; 
      return accesor.GetValue(data, null); 
     } 
     string[] innerElements = elements.Skip(1).ToArray(); 
     object innerData = data.GetType().GetProperty(elements[0]).GetValue(data); 
     return GetItem(innerData, innerElements, out itemType); 
    }