C# 是否对CollectionViewSource使用多个排序描述?
我有一个定义了排序描述的CollectionViewSource,但是我想根据用户可以选择的单独下拉列表更改这些排序描述。理想情况下,我希望实现所有这些,而不需要代码落后C# 是否对CollectionViewSource使用多个排序描述?,c#,wpf,xaml,sorting,collectionviewsource,C#,Wpf,Xaml,Sorting,Collectionviewsource,我有一个定义了排序描述的CollectionViewSource,但是我想根据用户可以选择的单独下拉列表更改这些排序描述。理想情况下,我希望实现所有这些,而不需要代码落后 <CollectionViewSource x:Key="SortedPeople" Source="{Binding People}"> <!--sort by first name then last name --> <CollectionViewSo
<CollectionViewSource x:Key="SortedPeople" Source="{Binding People}">
<!--sort by first name then last name -->
<CollectionViewSource.SortDescriptions>
<scm:SortDescription PropertyName="FirstName"/>
<scm:SortDescription PropertyName="LastName"/>
</CollectionViewSource.SortDescriptions>
<!-- another way to do this?
<!--sort by last name then first name -->
<CollectionViewSource.SortDescriptions>
<scm:SortDescription PropertyName="LastName"/>
<scm:SortDescription PropertyName="FirstName"/>
</CollectionViewSource.SortDescriptions>-->
</CollectionViewSource>
(...xaml for drop down box which sets which set of sort descriptions to use...)
-->
(…用于设置要使用的排序描述集的下拉框的xaml…)
有可能吗?假设您有一个带有多个排序参数的组合框
<ComboBox ItemsSource="{Binding SortByItemList}"
SelectedItem="{Binding SelectedSortByItem,Mode=TwoWay}"/>
在视图模型中,放置以下内容:
public string SelectedSortByItem
{
get
{
return _selectedSortByItem;
}
set
{
_selectedSortByItem = value;
OnSelectedSortByItemChanged(People, SelectedSortByItem);
RaisePropertyChanged();
}
}
public IList<People> OnSelectedSortByItemChanged(IList<People> items, string sortBy)
{
if (items == null || !items.Any())
{
return items;
}
var itemsToSort = items.ToList();
if (sortBy == "FirstName")
{
return Sort(itemsToSort, "FirstName");
}
else if (sortBy == "LastName")
{
return Sort(itemsToSort, "LastName");
}
// put as many properties as you want here
}
private static List<People> Sort(
List<People> itemsToSort,
string propertyPath,
ListSortDirection sortDirection = ListSortDirection.Ascending)
{
// put your sorting logic here.
}
public string SelectedSortByItem
{
得到
{
返回_selectedSortByItem;
}
设置
{
_selectedSortByItem=值;
OnSelectedSortByItemChanged(人员,SelectedSortByItem);
RaisePropertyChanged();
}
}
公共IList OnSelectedSortByItemChanged(IList项,字符串排序)
{
if(items==null | |!items.Any())
{
退货项目;
}
var itemsToSort=items.ToList();
如果(排序方式==“FirstName”)
{
返回排序(itemsToSort,“FirstName”);
}
else if(排序方式==“LastName”)
{
返回排序(itemsToSort,“LastName”);
}
//在此处放置任意数量的属性
}
私有静态列表排序(
列表项排序,
字符串属性路径,
ListSortDirection-sortDirection=ListSortDirection.升序)
{
//把你的分类逻辑放在这里。
}
希望这有帮助