我正在尝试创建一个简单的程序,您可以将汽车添加到列表中并查看make模型和年份。在我的xaml主窗口中,我有3个文本框来收集用户的信息:
<TextBox Text="{Binding NewCar.Model}"/>
<TextBox Text="{Binding NewCar.Make}"/>
<TextBox Text="{Binding NewCar.Year}"/>
然后用户点击&#34;添加&#34;按钮和汽车应该添加到列表中:
<Button Content="Add" Command="{Binding TouchCommand}" CommandParameter="{Binding NewCar}"/>
我已经验证了触摸命令正常添加汽车但是,似乎潜在的问题是文本框没有将输入到它们的内容绑定到NewCar对象的相应属性,因为当我点击添加按钮参数仍然为空。
这是add的执行方法:
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");
}
}
这是我的viewmodel中的相关代码:
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));
}
}
}
}
答案 0 :(得分:2)
为什么要传递参数?您可以将TextBox绑定到ViewModel的属性,然后在add new car命令中,根据ViewModel中已有的信息创建一个新车。有很多方法可以做到这一点,但个人喜好是不要在按钮命令中传递参数,除非你必须这样做。祝你好运!
答案 1 :(得分:1)
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
}
答案 2 :(得分:0)
似乎问题是我没有任何地方可以获取信息,因为我没有在viewmodel中初始化newCar对象。我必须使用空字符串创建一个0参数构造函数,一切正常!