How can I get a DataGrid to sort it's backing ObservableCollection when the grid itself is sorted?
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 prope开发者_高级运维rty for a child control which in this case shows the incorrect object.
I've managed to solve this by using both SelectedIndex
and SelectedItem
binding properties and not navigating through the list itself.
View:
<DataGrid Name="gridCustomers"
ItemsSource="{Binding Path=Customers}"
SelectedIndex="{Binding SelectedIndex}"
SelectedItem="{Binding SelectedCustomer}"
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("NavText");
}
}
}
private Customer selectedCustomer;
public Customer SelectedCustomer {
get { return selectedCustomer; }
set {
if (!Object.Equals(selectedCustomer, value)) {
selectedCustomer = value;
OnNotifyPropertyChanged("SelectedCustomer");
}
}
}
public string NavText {
get {
if (Customers.Count == 0)
return "No Customers";
if (SelectedIndex == -1)
return String.Format("{0} customers", customers.Count);
return String.Format("{0} of {1}", SelectedIndex + 1, Customers.Count);
}
}
public void First() {
if (Customers.Count == 0)
return;
SelectedIndex = 0;
}
public void Last() {
if (Customers.Count == 0)
return;
SelectedIndex = Customers.Count - 1;
}
public void Next() {
if (Customers.Count == 0 || SelectedIndex == Customers.Count - 1)
return;
SelectedIndex++;
}
public void Previous() {
if (Customers.Count == 0 || SelectedIndex <= 0)
return;
SelectedIndex--;
}
精彩评论