当网格本身排序时,如何让 DataGrid 对其支持的 ObservableCollection 进行排序?
我有一个绑定到对象列表的网格,SelectedIndex
绑定到一个属性,我希望这个 SelectedIndex
能够在排序时索引更改时正常工作,但是集合模型内未排序,因此索引与模型无关。
视图中的标记:
<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>
模型中的代码
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]; }
}
我使用这种方法是因为我有“下一个/上一个”按钮和一个绑定到“x of y 客户”的标签。 SelectedCustomer
是子控件的一个便利属性,在本例中显示了不正确的对象。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我设法通过使用
SelectedIndex
和SelectedItem
绑定属性来解决此问题,而不是通过列表本身进行导航。视图:
型号:
I've managed to solve this by using both
SelectedIndex
andSelectedItem
binding properties and not navigating through the list itself.View:
Model: