c# - 将多个 DataBindings 添加到 Winforms 标签

标签 c# winforms data-binding

我在 Label 控件中显示不同的值,该控件来自绑定(bind)到 DataGridViewBindingSource,具体取决于选择的行。

现在,标签有一个如下所示的数据绑定(bind):

this.label9.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.bev_BindingSource, "countryRegion", true));

它成功显示了 countryRegion 列的值。

是否可以将数据绑定(bind)设置为两列的串联结果,在本例中为 countryRegioncountry

最佳答案

您需要使用 MultiBinding .添加两个 Binding 实例(一个用于 countryRegion,一个用于 country)。然后你需要实现一个 IMultiValueConverter 来接受两个绑定(bind)对象生成的值并将它们转换为单个值。

绑定(bind)设置看起来像这样:

var multiBinding = new MultiBinding();
multiBinding.Bindings.Add(new Binding("Text", this.bev_BindingSource, "countryRegion", true));
multiBinding.Bindings.Add(new Binding("Text", this.bev_BindingSource, "country", true));
multiBinding.Converter = new MyMultiValueConverter();

this.label9.DataBindings.Add(multiBinding);

转换器的实现看起来像这样:

public class MyMultiValueConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        // perform your conversion here and return the final value
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

关于c# - 将多个 DataBindings 添加到 Winforms 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20434312/

相关文章:

Android Studio 2.2 数据绑定(bind)错误

c# - 正确的骨料设计和复杂的规范查询

c# - 如何在 C# 中执行表 SP

c# - 在 native 函数回调线程上运行异步任务继续

c# - 尝试在网站上获取歌曲列表不起作用

c# - WinForms - 如何获得控件 "wants"的大小?

c# - 为什么 TreeView 控件不绑定(bind)

c# - 为什么我不能使 BackgroundWorker() 按预期工作?

c# - 可访问性不一致

c# - c#对象间数据传递