且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Winforms中使用数据绑定中的ValueConverter

更新时间:2023-10-19 19:35:58

你可以如果您能够并愿意装饰数据源,请使用 TypeConverter 属性具有自定义属性。

You can use a TypeConverter if you're able and willing to decorate the data source property with a custom attribute.

否则,您必须附加到 Parse 格式 绑定 对象。这不幸的是,除了最简单的情况之外,消除了使用设计器进行绑定。

Otherwise you have to attach to the Parse and Format events of a Binding object. This, unfortunately, eliminates using the designer for your binding for all but the simplest scenarios.

例如,假设你想要一个 TextBox 绑定到一个表示公里的整数列,你想要视觉表示以英里为单位:

For example, let's say you wanted a TextBox bound to an integer column representing kilometers and you wanted the visual representation in miles:

在构造函数中:

Binding bind = new Binding("Text", source, "PropertyName");

bind.Format += bind_Format;
bind.Parse += bind_Parse;

textBox.DataBindings.Add(bind);

...

void bind_Format(object sender, ConvertEventArgs e)
{
    int km = (int)e.Value;

    e.Value = ConvertKMToMiles(km).ToString();
}

void bind_Parse(object sender, ConvertEventArgs e)
{
    int miles = int.Parse((string)e.Value);

    e.Value = ConvertMilesToKM(miles);
}