I have a grid bound to a list of objects, the SelectedIndex is bound to a property, I wish this SelectedIndex which works correctly as the index changes on sorting, however the collection within the model does not get sorted, so the index does not relate to the model.
Markup in view:
<DataGrid Name="gridCustomers"
ItemsSource="{Binding Customers}"
SelectedIndex="{Binding SelectedIndex}"
CanUserSortColumns="True"
SelectionUnit="FullRow">
<DataGrid.Columns>
<DataGridTextColumn Header="Customer" Binding="{Binding ID}" />
<DataGridTextColumn Header="Name" Binding="{Binding Name}" />
</DataGrid.Columns>
</DataGrid>
Code in model
public ObservableCollection<Customer> Customers {
get;
private set;
}
private int selectedIndex;
public int SelectedIndex {
get { return selectedIndex; }
set {
if (selectedIndex != value) {
selectedIndex = value;
OnNotifyPropertyChanged("SelectedIndex");
OnNotifyPropertyChanged("SelectedCustomer");
}
}
}
public Customer SelectedCustomer {
get { return CustomersView[selectedIndex]; }
}
I’m using this approach because I have “next/previous” buttons and a label binding to “x of y customers”. The SelectedCustomer is a convenience property for a child control which in this case shows the incorrect object.
I’ve managed to solve this by using both
SelectedIndexandSelectedItembinding properties and not navigating through the list itself.View:
Model: