上下文在资源部分引用我的ViewModel
<DataGrid DataContext="{StaticResource TheContext}"
ItemsSource="{Binding Path=Cars}">
这是我的viewModel.cs
public CarsSearchResultsViewModel()
{
ButtonCommand = new DelegateCommand(x => GetCars());
}
public void GetCars()
{
List<Car> cars = new List<Car>();
cars.Add(new Car() { Make = "Chevy", Model = "Silverado" });
cars.Add(new Car() { Make = "Honda", Model = "Accord" });
cars.Add(new Car() { Make = "Mitsubishi", Model = "Galant" });
Cars = new ObservableCollection<Car>(cars);
}
private ObservableCollection<Car> _cars;
public ObservableCollection<Car> Cars
{
get { return _cars; }
private set
{
if (_cars == value) return;
_cars = value;
}
}
我试过添加OnPropertyChanged("Cars")
,我试过在添加列表之前添加People = null
,我试过将UpdateSourceTrigger=PropertyChanged
添加到ItemsSource,在使用ObservableCollection之前我试过使用IViewCollection
。
我不试图更新或删除从一个集合,只是填充一个按钮点击网格。如果我在没有命令的构造函数中运行GetCars()
,它可以正常工作。
你的ViewModel需要实现INotifyPropertyChanges
接口,并在ObservableCollection
的setter中调用OnpropertyChanged
,这样当你恢复UI时会得到通知,所以你的Cars属性应该看起来像这样:
private ObservableCollection<Car> _cars ;
public ObservableCollection<Car> Cars
{
get
{
return _cars;
}
set
{
if (_cars == value)
{
return;
}
_cars = value;
OnPropertyChanged();
}
}
Cars集合需要在 Context类中定义,因为它是您的Context,最后一个需要实现前面提到的接口:
public class TheContext:INotifyPropertyChanged
{
//Cars property and your code ..
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}