我有一个代表这样的汽车的类:
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 UI 中,我有一个对应于每个轮胎的 Size 属性的组合框(下拉列表)。我正在尝试将每个组合框绑定到相应轮胎的 Size 属性,但我一直用来绑定到汽车对象本身属性的代码不起作用。这是我用来将组合框绑定到汽车的 Color 属性的代码:
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”)上,但我不确定。我只是以错误的方式引用它,还是我在这里的方法完全错误?