通过按钮命令填充 DataGrid

Populate DataGrid through Button Command

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 之前我尝试使用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 集合需要在 TheContext class 中定义,因为它是您的上下文,最后一个需要实现上述接口:

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));
    }
}