【问题标题】:How do I use a ValueConverter with Databinding in Winforms如何在 Winforms 中使用带有数据绑定的 ValueConverter
【发布时间】:2011-02-08 19:41:10
【问题描述】:

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

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

【问题讨论】:

标签: winforms data-binding


【解决方案1】:

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

否则,您必须附加到 Binding 对象的 ParseFormat 事件。不幸的是,除了最简单的场景之外,这消除了使用设计器进行绑定。

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

在构造函数中:

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);
}

【讨论】:

  • 值得一提的是,该技术仅涵盖使用和暴露 Binding 对象的场景。它不适用于网格和其他复杂的绑定控件,除非它们当然有自己的 Format / Parse API。因此,不幸的是,在 WinForms 数据绑定机制中确实没有任何“通用”方式使用值转换器。
【解决方案2】:

另一种选择是为表单提供特定的 ViewModel,它以您需要在表单上显示的格式公开数据。您可以通过使用AutoMapper 并构建自己的Formatter 轻松实现它。

这样您也将获得对设计师的全面支持。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-28
    • 2011-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-01
    • 1970-01-01
    • 2011-03-30
    相关资源
    最近更新 更多