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));
原文地址:https://www.cnblogs.com/aning2015/p/9929945.html
时间: 2024-10-10 06:54:36