我有一个 ListBox,它可以使用代码隐藏 MVVM 对象来显示数据。但是,我想对条目进行排序,因此我认为中间的 CollectionViewSource 可能会起作用。但相反,程序在启动时崩溃。
原始 xaml 摘录:
<ListBox SelectedItem="{Binding SelectedCategory}"
DisplayMemberPath="name"
ItemsSource="{Binding Categories}"
Name="CategoriesListBox" />
提取后的代码:
public class ViewModel : INotifyPropertyChanged
{
private trainCategory[] _categories;
private trainCategory _selectedCategory;
public event PropertyChangedEventHandler PropertyChanged;
public trainCategory[] Categories
{
get { return _categories; }
set
{
if (_categories == value)
{
return;
}
_categories = value;
RaisePropertyChanged("Categories");
}
} //etc
列表框的替换 XAML:
<ListBox SelectedItem="{Binding SelectedCategory}"
DisplayMemberPath="name"
ItemsSource="{Binding Source={StaticResource SortedItems}}"
Name="CategoriesListBox" />
和 CollectionViewSource:
<CollectionViewSource x:Key="SortedItems" Source="{Binding Categories}">
<CollectionViewSource.SortDescriptions>
<scm:SortDescription PropertyName="name"/>
</CollectionViewSource.SortDescriptions>
</CollectionViewSource>
在我看来,CollectionViewSource 位于 View 模型和 ListBox 之间,但显然不是(或者我做错了)。任何指示表示赞赏。
最佳答案
使用原始的 xaml
<ListBox SelectedItem="{Binding SelectedCategory}"
DisplayMemberPath="name"
ItemsSource="{Binding Categories}"
Name="CategoriesListBox" />
更新 View 模型以使用列表:
public List<trainCategory> _categories;
public List<trainCategory> Categories
{
get
{ // This LINQ statement returns a sorted list
return (from c in _categories
orderby c
select c);
}
set
{
if (_categories == value)
{
return;
}
_categories = value;
RaisePropertyChanged("Categories");
}
} //etc
然后你就可以跳过尝试绑定(bind)到静态资源的所有麻烦事了。只需将 strait 绑定(bind)到 View 模型中的属性即可。
或者,您仍然可以在 View 模型中使用数组作为支持变量:
public trainCategory[] _categories;
public List<trainCategory> Categories
{
get
{ // This LINQ statement returns a sorted list
return (from c in _categories
orderby c
select c).ToList();
}
set
{
if (_categories == value.ToArray())
{
return;
}
_categories = value.ToArray();
RaisePropertyChanged("Categories");
}
} //etc
关于c# - 使用 MVVM 代码绑定(bind)对 ListBox 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7600331/