我有一个CollectionViewSource,其中定义了排序说明,但我想根据用户可以选择的单独下拉列表更改这些排序说明。理想情况下,我希望在没有代码隐藏的情况下实现所有这些。
<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...)
有可能吗?
答案 0 :(得分:0)
假设你有一个带有多个排序参数的组合框。
<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.
}
希望这有帮助。