获取绑定的基础数据类型 [英] Get underlying data type of binding

查看:79
本文介绍了获取绑定的基础数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How to get the underlying data type of a bound property?

出于测试目的,我创建了一个视图模型 Person,其属性为Int32类型的年龄,

For testing purposes I created a viewmodel 'Person' with a property 'Age' of type Int32, that is bound to a textbox's text property.

是否有类似...

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

还是可以提供此信息只能通过反射检索?

or can this information only be retrieved by reflection?

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

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

I have a custom textbox class, where I want to attach my own validationrules, converters ...

最好在fe中获取信息

推荐答案

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

The only way I have found to do this is by using reflection. The following code gets the binded object. It also handles nested binding {Binding Parent.Value} and if a converter is present - it returns the converted value. The method also returns the item's type for the cases in which the item is 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);
    }

这篇关于获取绑定的基础数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆