gpt4 book ai didi

c# - 如何按一个属性对 CollectionViewSource 进行排序,然后按另一个属性排序作为决胜局?

转载 作者:可可西里 更新时间:2023-11-01 07:49:55 27 4
gpt4 key购买 nike

目前,我的 CollectionViewSource 按描述对项目集合进行排序。如果描述相同,我想根据ID排序。如何指定先按描述排序,然后按 ID 排序?

我尝试添加第二个带有 PropertyName="Id"的 SortDescription,但没有成功。

 <CollectionViewSource x:Key="Items" Source="{Binding Items}" >
<CollectionViewSource.SortDescriptions>
<scm:SortDescription PropertyName="Description"/>
</CollectionViewSource.SortDescriptions>
</CollectionViewSource>

编辑: ID 属性在 View 模型上是私有(private)的。没有抛出任何错误。

最佳答案

我不确定为什么为 Id 添加 SortDescription 不起作用,因为它应该可以正常工作。

像这样:

<CollectionViewSource x:Key="Items" Source="{Binding ElementName=UI, Path=Items}" >
<CollectionViewSource.SortDescriptions>
<scm:SortDescription PropertyName="Description" />
<scm:SortDescription PropertyName="Id" />
</CollectionViewSource.SortDescriptions>
</CollectionViewSource>

我根据您的需要整理了一个完整的示例:

Xaml:

<Window x:Class="WpfApplication7.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase"
Title="MainWindow" Height="124" Width="464" Name="UI" >
<Window.Resources>

<CollectionViewSource x:Key="Items" Source="{Binding ElementName=UI, Path=Items}" >
<CollectionViewSource.SortDescriptions>
<scm:SortDescription PropertyName="Description" />
<scm:SortDescription PropertyName="Id" />
</CollectionViewSource.SortDescriptions>
</CollectionViewSource>
</Window.Resources>

<Grid>
<ListBox ItemsSource="{Binding Source={StaticResource Items}}" />
</Grid>

代码:

public partial class MainWindow : Window
{
private ObservableCollection<MyObject> myVar = new ObservableCollection<MyObject>();

public MainWindow()
{
InitializeComponent();
Items.Add(new MyObject { Description = "Stack", Id = 5 });
Items.Add(new MyObject { Description = "OverFlow", Id = 1 });
Items.Add(new MyObject { Description = "StackOverFlow", Id = 2 });
Items.Add(new MyObject { Description = "Stack", Id = 1 });
Items.Add(new MyObject { Description = "Stack", Id = 0 });
Items.Add(new MyObject { Description = "OverFlow", Id = 7 });
}

public ObservableCollection<MyObject> Items
{
get { return myVar; }
set { myVar = value; }
}
}


public class MyObject
{
public int Id { get; set; }
public string Description { get; set; }

public override string ToString()
{
return string.Format("Desc: {0}, Id: {1}", Description, Id);
}
}

结果:

enter image description here

关于c# - 如何按一个属性对 CollectionViewSource 进行排序,然后按另一个属性排序作为决胜局?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14992072/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com