两个类之间的数据绑定
本文关键字:之间 数据绑定 两个 | 更新日期: 2023-09-27 18:34:04
对象:在三个类之间使用数据绑定
环境: Visual Studio 2012, C#, WindowsForms
错误:数据绑定在我的类中不起作用
预期成果:
对象:
- 高度:数量
- 基数:数量
- 区域:配方
- 面积结果:结果
数据绑定:
Area.DataBindings.Add("H",Height,"Q");
Area.DataBindings.Add("B",Base,"Q");
AreaResult.DataBindings.Add("Display",Area,"Calculation");
Height.Q = 5;
Base.Q = 6;
应该产生该Area.Calculation
设置为 30 和 AreaResult.Display
。
班级数量代码:
public class Quantity:INotifyPropertyChanged
{
public Nullable<decimal> Q
{
get{ return this._q;}
set
{
this._q = value;
NotifyPropertyChanged("Q");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged(string name)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
}
类制定代码:
public class Formulate: INotifyPropertyChanged
{
public Nullable<decimal> H
{
get { return this._h; }
set
{
this._h = value;
NotifyPropertyChanged("H");
}
}
private Nullable<decimal> _h;
public Nullable<decimal> Q
{
get { return this._q; }
set
{
this._q = value;
NotifyPropertyChanged("Q");
}
}
private Nullable<decimal> _h;
public Nullable<decimal> Calculation
{
get { return this._calculation; }
set
{
this._calculation = H/Q;
NotifyPropertyChanged("Caltulation");
}
}
private Nullable<decimal> _calculation;
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged(string name)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
}
类结果代码:
public class Result:INotifyPropertyChanged
{
public Nullable<decimal> Display
{
get{ return this._display;}
set
{
this._display = value;
NotifyPropertyChanged("Display");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged(string name)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
}
这应该可以解决问题:
public class Formulate: INotifyPropertyChanged
{
public Nullable<decimal> H
{
get { return this._h; }
set
{
this._h = value;
NotifyPropertyChanged("H");
NotifyPropertyChanged("Calculation");
}
}
private Nullable<decimal> _h;
public Nullable<decimal> Q
{
get { return this._q; }
set
{
this._q = value;
NotifyPropertyChanged("Q");
NotifyPropertyChanged("Calculation");
}
}
private Nullable<decimal> _h;
public Nullable<decimal> Calculation
{
get { return _h == null || _q == null ? null : _h.Value / _q.Value; }
}
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged(string name)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
}