【问题标题】:Add multiple DataBindings to Winforms label将多个 DataBindings 添加到 Winforms 标签
【发布时间】:2013-12-06 21:57:17
【问题描述】:

我在 Label 控件中显示与绑定到 DataGridViewBindingSource 不同的值,具体取决于选择的行。

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

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

成功显示countryRegion 列的值。

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

【问题讨论】:

    标签: c# winforms data-binding


    【解决方案1】:

    您需要使用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();
        }
    }
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 我发现这种方法更简单,更容易调试,谢谢。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多