WinForm 绑定到嵌套对象上的属性
WinFrom 绑定到嵌套对象上的属性
关键字: Windows Forms, DataBindings, Nested Class, 嵌套类
在 WinForm 中很早就已经支持数据绑定, 使用数据绑定可以大大减少更新界面和数据的代码.
一般情况下, 使用自定义的简单对象时数据绑定可以很好的工作, 当我们的对象越来越复杂, 一个对象中使用另一个对象作为属性时, 简单的数据绑定已经无法满足需求.
例如有下面两个对象:
/// <summary>
/// 外部实体
/// </summary>
public class Outer : INotifyPropertyChanged
{
#region - Private -
private string _name;
private Inner _inner;
#endregion
public event PropertyChangedEventHandler PropertyChanged;
public string Name
{
get { return this._name; }
set
{
if(value != this._name)
{
this._name = value;
RaisePropertyChanged();
}
}
}
public Inner Inner
{
get { return this._inner; }
set
{
if(value != this._inner)
{
this._inner = value;
RaisePropertyChanged();
}
}
}
private void RaisePropertyChanged([CallerMemberName]string propertyName = null)
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
/// <summary>
/// 内部实体
/// </summary>
public class Inner : INotifyPropertyChanged
{
#region - Private -
private string _name;
#endregion
public event PropertyChangedEventHandler PropertyChanged;
public string Name
{
get { return this._name; }
set
{
if(value != this._name)
{
this._name = value;
RaisePropertyChanged();
}
}
}
private void RaisePropertyChanged([CallerMemberName]string propertyName = null)
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
数据绑定使用如下:
//初始化对象
var outer = new Outer();
//初始化绑定对象
var outerBindingSource = new BindingSource() { DataSource = outer };
var innerBindingSource = new BindingSource(outer, nameof(outer.Inner));
//绑定到控件
this.textBoxName.DataBindings.Add("Text", outerBindingSource, nameof(outer.Name));
this.textBoxInnerName.DataBindings.Add("Text", innerBindingSource, nameof(outer.Inner.Name));
更新: ComboBox 绑定枚举. comboBox 选择项更改时, 绑定对象的枚举属性同样更改
//1. 设置 ComboBox 数据源
this.comboBox.DataSource = Enum.GetValues(typeof(CustomEnum));
this.comboBox.SelectedIndex = 0;
//2. 设置绑定
this.comboBox.DataBindings.Add(nameof(this.comboBox.SelectedItem), bindingSource, nameof(bindingSource.CustomEnumProperty));