【发布时间】:2015-05-21 22:49:34
【问题描述】:
我有一个列表框,我希望在将项目添加到列表时对其进行更新。我知道我需要绑定列表框。我试图关注这个question/answer。
我有一个处理列表的 ViewModel:
namespace TESTS
{
public class ViewModel : INotifyPropertyChanged
{
private List<Cars> _listCars;
public List<Cars> listCars
{
get
{
return _listCars;
}
set
{
if (_listCars == value)
{
return;
}
this.RaisePropertyChanged("Message");
_listCars = value;
this.RaisePropertyChanged("Message");
}
}
public ViewModel()
{
listCars = new List<Cars>();
}
protected void RaisePropertyChanged(string propertyName)
{
Debug.WriteLine("Property Changed");
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
这是汽车类:
public class Cars: INotifyPropertyChanged
{
public string model{ get; set; }
public string year{ get; set; }
public event PropertyChangedEventHandler PropertyChanged;
}
所以我将列表框绑定到我的 Viewmodel 中的属性路径,即 listCars。
<ListBox .... ItemsSource="{Binding listCars}">
所以当在我的 Main.xaml.cs 中时。我单击按钮并添加项目。即使它绑定到视图模型上的列表,它也不会被添加到列表框。
public sealed partial class MainPage : Page
{
public static ViewModel vm = new ViewModel();
public MainPage()
{
this.InitializeComponent();
this.DataContext = vm;
}
private void button_Click(object sender, RoutedEventArgs e)
{
Cars x = new Cars();
x.model = "Ford";
x.Year = "1998";
vm.listCars.Add(x);
}
}
我希望我能很好地解释我实施的内容。我的 ViewModel 实现有问题吗?我是 MVVM 的新手。请帮忙。
【问题讨论】:
-
只要使用
ObservableCollection<T>,它就会解决你所有的问题。 -
但是 List
不可能吗?
标签: c# xaml mvvm listbox windows-store-apps