我有一个代表汽车的类,它长这样:
public class Car
{
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged([CallerMemberName] string caller = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(caller));
}
}
public enum Colors
{
LaserRed,
GenuineGraniteMica,
BluePearl,
SandMicaMetallic,
NightArmorMetallic
}
private string _make;
public string Make
{
get { return _make; }
set {
_make = value;
RaisePropertyChanged();
}
}
private string _model;
public string Model
{
get { return _model; }
set {
_model = value;
RaisePropertyChanged();
}
}
private Colors _color;
public Colors Color
{
get { return _color; }
set {
_color = value;
RaisePropertyChanged();
}
}
public Tire FrontLeftTire = new Tire();
public Tire FrontRightTire = new Tire();
public Tire RearLeftTire = new Tire();
public Tire RearRightTire = new Tire();
public Car()
{
// initialization code
}
如您所见,我的Car类有四个轮胎,而Tire类则如下所示:
public class Tire : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged([CallerMemberName] string caller = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(caller));
}
}
public enum SizeValues
{
[Description("17 inches")]
SeventeenInches,
[Description("18 inches")]
EighteenInches,
[Description("19 inches")]
NineteenInches,
[Description("20 inches")]
TwentyInches,
}
private string _brand;
public string Brand
{
get { return _brand; }
set
{
_brand = value;
RaisePropertyChanged();
}
}
private SizeValues _size;
public SizeValues Size
{
get { return _size; }
set
{
_size = value;
RaisePropertyChanged();
}
}
public Tire()
{
// initialization code
}
在我的WinForms用户界面中,我有一个下拉框(dropdownlist),它对应于每个轮胎的尺寸属性。 我正在尝试将每个下拉框绑定到相应轮胎的尺寸属性,但我之前用来绑定汽车对象本身属性的代码不起作用。 这是我用来将下拉框绑定到汽车颜色属性的代码:
comboBoxCarColor.DataBindings.Add(new Binding("SelectedValue", bindingSourceForCars, "Color", true, DataSourceUpdateMode.OnPropertyChanged));
comboBoxCarColor.DataSource = new BindingSource(Utility.ConvertEnumToListOfKeyValuePairs(typeof(Car.Color)), null);
comboBoxCarColor.DisplayMember = "Value";
comboBoxCarColor.ValueMember = "Key";
这个没问题。但我觉得现在遇到的问题是,我试图绑定到一个不是汽车直接子属性的属性,而是汽车轮胎的属性。所以,像这样的东西不起作用:
comboBoxFrontLeftTimeSize.DataBindings.Add(new Binding("SelectedValue", bindingSourceForCars, "FrontLeftTire.Size", true, DataSourceUpdateMode.OnPropertyChanged));
我认为问题出在数据成员"FrontLeftTire.Size"上,但我不确定。这是我的引用方式有误还是我的方法完全错误呢?