将字符串属性绑定到对象 [英] Binding string property to object

查看:33
本文介绍了将字符串属性绑定到对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一堂这样的课:

Say I have a class like this:

public class MyClass
{
    public string Name;
    public int Id;

    public override string ToString()
    {
        return this.Id.ToString() + " - " + this.Name;
    }
}

如果我将数据网格文本列绑定到此类的对象实例(不使用转换器),则会调用覆盖的 ToString 并成功显示 Id - Name.但是,当我将同一个对象绑定到 TextBlock 的 Text 属性时,永远不会调用 ToString 并且 Text 为空.我知道我可以使用转换器,但我试图理解为什么绑定不会像绑定到数据网格列时那样调用 ToString.

If I bind a datagrid text column to an object instance of this class (without using a converter), the overridden ToString is called and displays the Id - Name successfuly. However, when I bind the same object to a TextBlock's Text property, the ToString is never called and Text is empty. I know I could use a converter, but I'm trying to understand why the binding doesn't call the ToString like it does when I bind to the datagrid column.

Datagrid 列绑定(datagrid 的项源是 MyClass 对象的集合):

Datagrid column binding (datagrid's item source is a collection of MyClass objects):

<DataGridTextColumn Binding="{Binding .}" Header="Id - Name"/>

TextBlock 绑定:

TextBlock binding:

<TextBlock><Run Text="{Binding myClass, ElementName=UserControl}"/></TextBlock>

注意:如果我将 myClass 更改为 myClass.Name,那么它会成功显示 Name 属性.

Note: if I change myClass to myClass.Name, then it successfully displays the Name property.

推荐答案

如果绑定类型不匹配,WPF 将对某些转换应用隐式转换器.可以通过调用 ToString() 以与在 .Net 框架的其他区域中隐式调用相同的方式来转换为字符串.

There are certain conversions for which WPF will apply an implicit converter on a binding if the bound types don't match. Converting to a string can be done by calling ToString() the same way it's implicitly called in other areas of the .Net framework.

TextBox 的 Text 绑定默认是双向的,因此不能使用隐式转换器,因为字符串不能转换回 MyClass 类型.网格列中显示模板的绑定是一种方式,因此可以使用隐式转换器.我想如果您通过单击将网格列置于编辑模式,您会收到绑定错误.

The Text binding of the TextBox is two-way by default and therefore can't use an implicit converter as a string can't be converted back to your MyClass type. The binding for the display template in the grid column is one way and can therefore use an implicit converter. I would imagine that you would get a binding error if you put the grid column into edit mode by clicking on it.

这篇关于将字符串属性绑定到对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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