TheContext指的是资源部分中的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之前我尝试使用{{ 1}}。
我没有尝试更新或删除集合,只需单击按钮填充网格即可。如果我在没有命令的构造函数中运行IViewCollection
它可以正常工作。
答案 0 :(得分:0)
您的ViewModel需要实现INotifyPropertyChanges
界面,并在OnpropertyChanged
的设置器中调用ObservableCollection
,这样当您恢复用户界面时会收到通知,因此您的汽车属性应该看起来有些想法像这样:
private ObservableCollection<Car> _cars ;
public ObservableCollection<Car> Cars
{
get
{
return _cars;
}
set
{
if (_cars == value)
{
return;
}
_cars = value;
OnPropertyChanged();
}
}
需要在 TheContext 类中定义Cars集合,因为它是您的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));
}
}