开发者

WPF SelectedItem not working in MVVM

I'm trying to display the data from two sql ce 3.5 sp1 database tables linked with foreign key - Customers and Orders. When the customer is selected in a datadrig, I want the other grid to be populated with the Orders. I'm using a 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 looks like this:

<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'm 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 it is ok. Thanks for any suggestions.


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'll want the ViewModel to implement INotifyPropertyChanged so it'll 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));
    }
}


If Martin's answer doesn't help, have a look at the DataGrid.SelectionUnit and make sure it is set to "FullRow" not to "CellOrRowHeader" like I had it.

If you have it set to "CellOrRowHeader", the first click on a cell will set the SelectedItem to null. I thought I'd add this in case someone else had the same annoying issue.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜