将多个DataBinding添加到Winforms标签

时间:2013-12-06 21:57:17

标签: c# winforms data-binding

我在绑定到Label的{​​{1}}的{​​{1}}控件中显示不同的值,具体取决于所选的行。

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

BindingSource

成功显示DataGridView列的值。

是否可以将数据绑定设置为两列的连续结果,在本例中为this.label9.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.bev_BindingSource, "countryRegion", true)); countryRegion

2 个答案:

答案 0 :(得分:4)

您需要使用MultiBinding。添加两个Binding个实例(一个用于countryRegion,一个用于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);

转换器实现看起来像:

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

答案 1 :(得分:3)

您可以创建一个计算属性并绑定到它。例如,创建一个返回值的Location属性,并绑定到它

public class MyData
{
    public string CountryRegion {get;set;}
    public string Country {get; set;}

    public string Location
    get()
    { 
      return CountryRegion+" " + Country;
    }
}