如何在Winforms中使用数据绑定中的ValueConverter [英] How do I use a ValueConverter in with Databinding in Winforms

查看:83
本文介绍了如何在Winforms中使用数据绑定中的ValueConverter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在WPF中,使用ValueConverter格式化值可以很容易(在我们的例子中,将一些数字转换成不同的单位,例如km到里程)

In WPF it is easy to use a ValueConverter to format values etc, (in our case convert some numbers into a different unit, e.g km to miles)

知道它可以在Winforms中完成,但是我所有的Googleing只是为WPF和Silverlight提供了结果。

I know it can be done in Winforms, but all my Googleing just brings up results for WPF and Silverlight.

推荐答案

你可以如果您能够并愿意装饰数据源,请使用 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);
}

这篇关于如何在Winforms中使用数据绑定中的ValueConverter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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