我在 Label
控件中显示不同的值,该控件来自绑定(bind)到 DataGridView
的 BindingSource
,具体取决于选择的行。
现在,标签有一个如下所示的数据绑定(bind):
this.label9.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.bev_BindingSource, "countryRegion", true));
它成功显示了 countryRegion
列的值。
是否可以将数据绑定(bind)设置为两列的串联结果,在本例中为 countryRegion
和 country
?
最佳答案
您需要使用 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/