获取绑定的基础数据类型

时间:2013-04-29 13:50:44

标签: wpf data-binding reflection

如何获取绑定属性的基础数据类型?

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

有什么类似......

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

或者这些信息只能通过反思来检索吗?

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

编辑: 我有一个自定义文本框类,我想附加我自己的验证规则,转换器......

获取f.e内的信息会很棒。文本框类的'load'事件。

3 个答案:

答案 0 :(得分:0)

您可以在转换器的Convert方法中获取值:

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}}"

不确定您需要访问该类型的位置,但如果您需要转换该值,则该级别可用。

答案 1 :(得分:0)

如果属性绑定到特定数据类型,则需要在文本框中将值设置为属性的有效值,然后才能更新viewmodel源

似乎任何验证错误都会停止视图模型更新。我认为这是垃圾。

答案 2 :(得分:0)

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

    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);
    }
相关问题