winforms - 如何在 Winforms 中使用带有数据绑定(bind)的 ValueConverter

标签 winforms data-binding

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

我知道它可以在 Winforms 中完成,但我所有的谷歌搜索只是为 WPF 和 Silverlight 带来了结果。

最佳答案

您可以use a TypeConverter 如果您能够并且愿意使用自定义属性来装饰数据源属性。

否则,您必须附加到 Parse Format Binding 的事件目的。不幸的是,除了最简单的场景之外,这消除了使用设计器进行绑定(bind)的可能性。

例如,假设您想要 TextBox绑定(bind)到表示公里的整数列,并且您想要以英里为单位的视觉表示:

在构造函数中:

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 - 如何在 Winforms 中使用带有数据绑定(bind)的 ValueConverter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2652875/

相关文章:

c# - WinForms DataGridView 即时保存到 Entity Framework 表格

c# - MS Chart 中的插值实现

c# - "Please Select"的数据绑定(bind)下拉列表不起作用

c# - 将字体高度设置为文本 block 高度的一半

c# winforms显示ffmpeg输出

java - 基本的 Spring MVC 数据绑定(bind)

data-binding - Xamarin.Forms 刷新编辑器的 TextProperty

delphi - Delphi 6 中绑定(bind)到数据库的多选列表框

android - 数据绑定(bind)错误 : old values should be followed by new values. 参数 2 必须与参数 3 的类型相同

c# - 在 Windows 窗体上绘制单个像素