我使用拖放将数据源对象(DB模型)绑定到 DataGrid (基本上遵循此示例 msdn.microsoft/en-us/data/jj574514 。一切都可以正常执行。
I used Drag and Drop to bind Data Source object (a DB model) to DataGrid (basically following this example msdn.microsoft/en-us/data/jj574514. Everything works fine with this implementation.
XAML:
<Window.Resources> <CollectionViewSource x:Key="categoryViewSource" d:DesignSource="{d:DesignInstance {x:Type local:Category}, CreateList=True}"/> </Window.Resources> <Grid DataContext="{StaticResource categoryViewSource}"> ..代码后面:
private void Window_Loaded(object sender, RoutedEventArgs e) { System.Windows.Data.CollectionViewSource categoryViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("categoryViewSource"))); _context.Categories.Load(); categoryViewSource.Source = _context.Categories.Local; }之后,我重构了应用程序并创建了一个ViewModel:
After that I refactor the application and create a ViewModel:
public MainWindow() { InitializeComponent(); this.DataContext = new MyViewModel(); }但是,当我尝试在ViewModel中使用相同的代码时,它不不工作( FindResource 不可用),此外,我不认为这是正确的方法(即使用 x:Key 在MVVM中)
However, when I try to use the same code from within ViewModel, it doesn‘t work (FindResource is not available), besides, I don’t think this is the right approach (i.e. to use x:Key in MVVM).
我真的很感激任何帮助,指出我正确的方法实现 CollectionViewSource 和 DataBinding 与 DataGrid 。
I would really appreciate any help to point me what is the right way to implement CollectionViewSource and DataBinding with DataGrid.
推荐答案您有两个选项可以使用MVVM正确使用 CollectionViewSource
You have two options to use CollectionViewSource properly with MVVM -
通过您的<$(类别)在您的案例中暴露 ObserVableCollection c $ c> ViewModel 并在xaml中创建 CollectionViewSource ,这样 -
Expose an ObserVableCollection of items (Categories in your case) through your ViewModel and create CollectionViewSource in xaml like this - <CollectionViewSource Source="{Binding Path=Categories}"> <CollectionViewSource.SortDescriptions> <scm:SortDescription PropertyName="CategoryName" /> </CollectionViewSource.SortDescriptions> </CollectionViewSource>
看到 - 使用CollectionViewSource从XAML中过滤收集
直接从您的 ViewModel
创建并公开一个 ICollectionView 请参阅 - 如何在WPF中浏览,分组,排序和过滤数据
see this - How to Navigate, Group, Sort and Filter Data in WPF
以下示例显示如何创建集合视图,将其绑定到 ListBox
Following example shows how to create a collection view and bind it to a ListBox
XAML:
<Window xmlns="schemas.microsoft/winfx/2006/xaml/presentation" xmlns:x="schemas.microsoft/winfx/2006/xaml"> <ListBox ItemsSource={Binding Customers} /> </Window>
查看Codebehind:
View Codebehind:
public class CustomerView { public CustomerView() { DataContext = new CustomerViewModel(); } }
ViewModel: / p>
ViewModel:
public class CustomerViewModel { private ICollectionView _customerView; public ICollectionView Customers { get { return _customerView; } } public CustomerViewModel() { IList<Customer> customers = GetCustomers(); _customerView = CollectionViewSource.GetDefaultView(customers); } }
更多推荐
在ViewModel中使用CollectionViewSource的正确方法
发布评论