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

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

问题描述

在WPF中,很容易使用ValueConverter格式化值等(在我们的示例中,将一些数字转换为不同的单位,例如,公里到英里)

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)

I知道可以在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 Format 事件 rel = nofollow noreferrer> 绑定 对象。不幸的是,除了最简单的方案之外,这消除了使用设计器进行绑定的麻烦。

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天全站免登陆