TheContext refers to my ViewModel in the resources section
<DataGrid DataContext="{StaticResource TheContext}"
ItemsSource="{Binding Path=Cars}">
This is my 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;
}
}
I have tried adding OnPropertyChanged("Cars")
, I have tried adding adding People = null
before adding the list, I have tried adding UpdateSourceTrigger=PropertyChanged
to the ItemsSource, and before using ObservableCollection I tried using IViewCollection
.
Im not trying to update or delete from a collection, just populate the grid with a button click. If i run GetCars()
in the constructor without the command it works fine.
Your ViewModel needs to implement the INotifyPropertyChanges
interface, and call OnpropertyChanged
in the setter of your ObservableCollection
so that when you reinstated the UI will get notified so you Cars property should looks somethink like this :
private ObservableCollection<Car> _cars ;
public ObservableCollection<Car> Cars
{
get
{
return _cars;
}
set
{
if (_cars == value)
{
return;
}
_cars = value;
OnPropertyChanged();
}
}
The Cars collection needs to be defined inside TheContext class since it is your Context and that last one needs to implement the mentioned interface :
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));
}
}