WPF SelectedItem not working in MVVM

I am trying to display data from two sql ce 3.5 sp1 database tables associated with a foreign key - clients and orders. When a client is selected in a datadrig, I want another grid to be filled with orders. I am using the query:

var profiles = from c in db.Customers.Include("Orders") select c; 

And in my ViewModel:

 private Models.Customers _selecteditem; public Models.Customers SelectedItem { get { return _selecteditem; } } 

the view is as follows:

 <Grid> <toolkit:DataGrid x:Name="dg1" ItemsSource="{Binding Customers}" SelectedItem="{Binding SelectedItem, mode=TwoWay}"> </toolkit:DataGrid> <toolkit:DataGrid x:Name="dg2" ItemsSource="{Binding Path=SelectedItem.Orders}"> </toolkit:DataGrid> </Grid> 

The error I am getting is:

 Warning 1 Field 'Clients.ViewModels.CustomerViewModel._selecteditem' is never assigned to, and will always have its default value null 

How to make it work correctly? When I just want to display Customers, everything is in order. Thanks for any suggestions.

+4
source share
2 answers

You need a setter for SelectedItem

 private Models.Customers _selecteditem; public Models.Customers SelectedItem { get { return _selecteditem; } set { _selectedItem = value; } } 

Also, since you are using it in a binding, you want the ViewModel to implement INotifyPropertyChanged , so this will actually be:

 private Models.Customers _selecteditem; public Models.Customers SelectedItem { get { return _selecteditem; } set { if (_selectedItem != value) { _selectedItem = value; NotifyPropertyChanged("SelectedItem"); } } } public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(String info) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(info)); } } 
+15
source

If Martin’s answer doesn’t help, look at DataGrid.SelectionUnit and make sure it is set to “ FullRow ” not to “CellOrRowHeader,” like mine.

If you have set the value to "CellOrRowHeader", the first click on the cell will set the SelectedItem value to null. I thought I would add this if someone has the same unpleasant problem.

+1
source

Source: https://habr.com/ru/post/1310226/


All Articles