我试图创建一个简单的程序,您可以在其中将汽车添加到列表中并查看品牌模型和年份.在我的xaml主窗口中,我有3个文本框来收集用户的信息:
<TextBox Text="{Binding NewCar.Model}"/>
<TextBox Text="{Binding NewCar.Make}"/>
<TextBox Text="{Binding NewCar.Year}"/>
然后,用户单击“添加”按钮,该车应添加到列表中:
<Button Content="Add" Command="{Binding TouchCommand}" CommandParameter="{Binding NewCar}"/>
我已经验证了touch命令可以正常添加汽车,但是似乎存在根本问题,因为文本框未将输入文本的内容绑定到NewCar对象的各个属性,因为当我单击添加按钮时,参数为仍然为空.
这是add的execute方法:
public void Execute(object parameter)
{
Car param = parameter as Car;
if (param != null)
{
lib.List.Add(param);
Console.WriteLine("{0} {1} {2}", param.Make, param.Model, param.Year);
}
else
{
Console.WriteLine("Param is null");
}
}
这是我的视图模型中的相关代码:
namespace CarApp
{
public class Carvm : INotifyPropertyChanged
{
private CarLib carLibrary;
private Car currentCar;
private DeleteCommand rmCommand;
private AddCommand touchCommand;
private Car newCar;
public Car NewCar
{
get { return newCar; }
set
{
newCar = value;
NotifyPropertyChanged("NewCar");
}
}
public Car CurrentCar
{
get { return currentCar; }
set
{
currentCar = value;
NotifyPropertyChanged("CurrentCar");
}
}
public CarLib CarLibrary
{
get { return carLibrary; }
set
{
carLibrary = value;
NotifyPropertyChanged("CarLibrary");
}
}
public DeleteCommand RMCommand
{
get { return rmCommand; }
set { rmCommand = value; }
}
public AddCommand TouchCommand
{
get { return touchCommand; }
set { touchCommand = value; }
}
public Carvm()
{
carLibrary = new CarLib();
carLibrary.List.Add(new Car("chevy", "corvette", "2016"));
carLibrary.List.Add(new Car("ford", "gt", "2016"));
carLibrary.List.Add(new Car("bmw", "m3", "2005"));
rmCommand = new DeleteCommand(carLibrary);
touchCommand = new AddCommand(carLibrary);
}
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
}
}
解决方法:
public Carvm()
{
carLibrary = new CarLib();
carLibrary.List.Add(new Car("chevy", "corvette", "2016"));
carLibrary.List.Add(new Car("ford", "gt", "2016"));
carLibrary.List.Add(new Car("bmw", "m3", "2005"));
rmCommand = new DeleteCommand(carLibrary);
touchCommand = new AddCommand(carLibrary);
NewCar = new Car(); // this line is added
}