如何更改使用MVVM DataGrid或列表视图内容视图、如何更改、内容、列表

2023-09-06 07:02:39 作者:初末慕流年

我有一个MainWindowViewModel(DataContext的),它暴露了不同ObservableCollections<>。经过从组合框中选择一个值(POCO对象与INotifyProperty ....中的ViewModels)我想点击一个按钮,加载,然后显示所需要的数据在数据网格或列表视图。问题是,在XAML $ C $词只能定义的ItemsSource和列具体定义为一个集合。那么,如何可以改变显示的方式,是符合MVVM数据。是否有任何的最佳做法?

I have a MainWindowViewModel (DataContext) which exposes different ObservableCollections<> (viewmodels of the poco objects with INotifyProperty.... ).After selecting a value from a combobox i want to click a load button which then displays the desired data in a datagrid or listview. Problem is, that in the xaml code i can only define the itemssource and column specific definitions for one collection. So how can i change the data that is displayed in way that is compliant with MVVM. Are there any best practices?

推荐答案

在你的视图模型创建暴露了一个的IEnumerable 属性。绑定DataGrid中的ItemsSource 到该属性。您可以设置,然后从视图模型内的财产,以任何你收集的,然后数据会发生变化。 请注意,您应该指定双向绑定,而你的财产必须支持一些更改通知(支持 INotifyPropertyChanged的或者是一个的DependencyProperty )。

Create in your ViewModel a property that exposes an IEnumerable. Bind the DataGrids ItemsSource to that property. You can set then the property from inside the ViewModel to any of your collections and then the data will change. Please note that you should specify two-way binding and that your property must support some change-notification (support INotifyPropertyChanged or be a DependencyProperty).