我已经在 MVVM 中为 WPF DataGrid 实现了 CollectionViewSource 的小演示。我非常感谢任何帮助来验证实现并评论这是否是使用 CollectionViewSource 的正确方法。
public class ViewModel : NotifyProperyChangedBase
{
private ObservableCollection<Movie> _movieList;
public ObservableCollection<Movie> MovieList
{
get { return _movieList; }
set
{
if (this.CheckPropertyChanged<ObservableCollection<Movie>>("MovieList", ref _movieList, ref value))
this.DisplayNameChanged();
}
}
private CollectionView _movieView;
public CollectionView MovieView
{
get { return _movieView; }
set
{
if (this.CheckPropertyChanged<CollectionView>("MovieView", ref _movieView, ref value))
this.DisplayNameChanged();
}
}
public ViewModel()
{
MovieView = GetMovieCollectionView(MovieList);
}
private void DisplayNameChanged()
{
this.FirePropertyChanged("DisplayName");
}
public void UpdateDataGrid(string uri)
{
MovieView = GetMovieCollectionView(new ObservableCollection<Movie>(MovieList.Where(mov => uri.Contains(mov.ID.ToString())).ToList<Movie>()));
}
public CollectionView GetMovieCollectionView(ObservableCollection<Movie> movList)
{
return (CollectionView)CollectionViewSource.GetDefaultView(movList);
}
XAML 视图:
<Window.Resources>
<CollectionViewSource x:Key="MovieCollection" Source="{Binding MovieList}">
</CollectionViewSource>
</Window.Resources>
<DataGrid Name="MyDG"
ItemsSource="{Binding MovieView}"
AutoGenerateColumns="True" />
背后的代码:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.Resources.Add("TagVM", new TagViewModel());
this.DataContext = this.Resources["TagVM"];
}
private void Hyperlink_Click(object sender, RoutedEventArgs e)
{
string uri = ((Hyperlink)sender).NavigateUri.ToString();
((ViewModel)this.DataContext).UpdateDataGrid(uri);
}
Hyperlink_Click 处理程序调用 VM 的 UpdateDataGrid 方法,将逗号分隔的电影 ID 传递给它,然后使用扩展方法过滤 MovieList 集合。