将多个数据绑定添加到 Winforms 标签

Dan*_*l B 5 c# data-binding winforms

我在Label控件中显示不同的值,从BindingSource绑定到 a 的 aDataGridView取决于选择了哪一行。

现在,标签具有如下所示的数据绑定:

this.label9.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.bev_BindingSource, "countryRegion", true));
Run Code Online (Sandbox Code Playgroud)

它成功地显示了countryRegion列的值。

是否可以从两列设置绑定为一个连接的结果,在这种情况下,countryRegioncountry

Mic*_*ter 5

您需要使用一个MultiBinding. 添加两个Binding实例(一个 forcountryRegion和一个 for country。然后您需要实现一个IMultiValueConverter将接受由两个绑定对象生成的值并将它们转换为单个值的。

绑定设置看起来像这样:

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);
Run Code Online (Sandbox Code Playgroud)

转换器实现看起来像:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)