【问题标题】:WPF Grid with an observablecollection as ItemsSource how to reorder it when a value in the collection is modified具有可观察集合作为 ItemsSource 的 WPF Grid 如何在修改集合中的值时对其重新排序
【发布时间】:2012-09-14 07:40:20
【问题描述】:

我是 WPF 的新手,我被一个我认为很容易解决的问题所困扰。 我有一个gridView(telerik one),它的ItemsSource是一个ObservableCollection,一切正常,当数据被修改时,我可以在网格中看到,当某些东西被删除或添加时,网格被刷新。 我的问题是,当集合更改时,更改的行转到网格中的最后一行,我需要对其重新排序,我尝试添加一个 SortDescriptor 以在更改集合时对网格进行排序,但没有任何反应。

//This update changes function is the one that changes the collection    
updateChanges(field, new_value);
//This is the sortDescriptor that is supposed to order the grid
UIGlobal.MainPage.gridAnalog.SortDescriptors.Add(new SortDescriptor()
{
     Member = "ColName",
     SortDirection = System.ComponentModel.ListSortDirection.Ascending
});

这是我的网格

<telerik:RadGridView>
   <telerik:RadGridView.Columns>
        <telerik:GridViewDataColumn UniqueName="ColName" Header="Name" DataMemberBinding="{Binding Key}"/>
        <telerik:GirdViewDataColumn Header="Value" DataMemberBinding="{Binding Value}"/>
   </telerik:RadGridView.Columns>
 </telerik:RadGridView>

我想从 ColName 列订购它,但无法得到它。

希望有人可以帮助我。 谢谢!

【问题讨论】:

  • 看看 ICollectionView 和 SortDescriptions

标签: wpf gridview


【解决方案1】:

我从未使用过 Telerik,但你可以试试这个:

//Add  reference  xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase"

<UserControll.Resources> 
 <CollectionViewSource Source="{Binding YourCollection}" x:Key="sorted">
     <CollectionViewSource.SortDescriptions>
         <scm:SortDescription  PropertyName="ColName" Direction="Ascending"/>
         </CollectionViewSource.SortDescriptions>
         </CollectionViewSource>

</UserControll.Resources>                               
<telerik:RadGridView  ItemsSource="{Binding Source={StaticResource sorted}}"> 
   <telerik:RadGridView.Columns>
        <telerik:GridViewDataColumn UniqueName="ColName" Header="Name" DataMemberBinding="{Binding Key}"/>
        <telerik:GirdViewDataColumn Header="Value" DataMemberBinding="{Binding Value}"/>
   </telerik:RadGridView.Columns>
 </telerik:RadGridView>

【讨论】:

  • 您好@igor,感谢您的重播,添加一个 sortDescriptor 是解决方案,但我需要一个 ColumnSortDescriptor 使其工作并通过代码完成
【解决方案2】:

这是我找到的解决方案,可能对某人有所帮助。 我在网格中添加了一个 ColumnSortDescriptor:

//Establish grid's ItemsSource
grid.ItemsSource = observableDicData;    
//Remove previous SortDescriptors
grid.SortDescriptors.Clear();
//Add a SortDescriptor
ColumnSortDescriptor csd = new ColumnSortDescriptor()
{
     //In column is the UniqueName of the grid's column I want to sort by
     Column = this.grid.Columns["NameAnalog"],
     SortDirection = ListSortDirection.Ascending
};
this.gridAnalog.SortDescriptors.Add(csd);

我禁用了 UserCanSort 的属性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多