我花了整个下午,但我终于找到了一个解决方案,它出奇地简单、短和高效:
要控制相关 UI 控件的行为(这里是 DataGrid),可以简单地使用 CollectionViewSource。它充当 ViewModel 中 UI 控件的一种代表,而不会完全破坏 MVMM 模式。
在 ViewModel 中声明一个 CollectionViewSource 和一个普通的 ObservableCollection<T> 并将 CollectionViewSource 包裹在 ObservableCollection 周围:
// Gets or sets the CollectionViewSource
public CollectionViewSource ViewSource { get; set; }
// Gets or sets the ObservableCollection
public ObservableCollection<T> Collection { get; set; }
// Instantiates the objets.
public ViewModel () {
this.Collection = new ObservableCollection<T>();
this.ViewSource = new CollectionViewSource();
ViewSource.Source = this.Collection;
}
然后在应用程序的 View 部分中,您无需将 CollectionControl 的 ItemsSource 绑定到 CollectionViewSource 的 View 属性,而不是直接绑定到 ObservableCollection:
<DataGrid ItemsSource="{Binding ViewSource.View}" />
从此时起,您可以在 ViewModel 中使用 CollectionViewSource 对象直接操作 View 中的 UI 控件。
例如排序——这是我的主要问题——看起来像这样:
// Specify a sorting criteria for a particular column
ViewSource.SortDescriptions.Add(new SortDescription ("columnName", ListSortDirection.Ascending));
// Let the UI control refresh in order for changes to take place.
ViewSource.View.Refresh();
你看,非常非常简单和直观。希望这可以帮助其他喜欢它帮助我的人。