【发布时间】:2019-06-12 15:09:24
【问题描述】:
我正在尝试将数据项的分组集合绑定到 DataGrid。呈现数据的细节无关紧要,实际上所有内容现在都是用虚拟数据设置的。
我按照Microsoft's Sample App 和"How to: Group, sort and filter data in the DataGrid Control" 中的示例代码进行操作。
启动应用程序后,显示的 DataGrid 为空,绑定代码的调试输出显示:
Error: Converter failed to convert value of type 'Windows.UI.Xaml.Data.ICollectionView' to type 'IBindableIterable'; BindingExpression: Path='MyContents' DataItem='MyViewModel'; target element is 'Microsoft.Toolkit.Uwp.UI.Controls.DataGrid' (Name='null'); target property is 'ItemsSource' (type 'IBindableIterable').
这是我的 XAML 中有趣的部分:
<mstkcontrols:DataGrid ItemsSource="{Binding MyContents}">
<!-- Irrelevant stuff left out... -->
</mstkcontrols:DataGrid>
在我的视图模型中,我有以下代码:
public ICollectionView MyContents { get; private set; }
public override void OnNavigatedTo(NavigationEventArgs e)
{
// Irrelevant stuff left out...
ObservableCollection<ObservableCollection<MyItemType>> groupedCollection = new ObservableCollection<ObservableCollection<MyItemType>>();
// It doesn't matter how this grouped collection is filled...
CollectionViewSource collectionViewSource = new CollectionViewSource();
collectionViewSource.IsSourceGrouped = true;
collectionViewSource.Source = groupedCollection;
MyContents = collectionViewSource.View;
}
是否有从ICollectionView 到IBindableIterable 的转换?如果有,是怎么做的?
我很清楚这些示例在代码中进行绑定,而不是在 XAML 中。这真的有影响吗?
如果这种方法是错误的,那么正确的方法是什么?
编辑:
对不起,我忘了提到我们使用的是"MVVM Light Toolkit" by GalaSoft。这就是为什么构建集合的代码在视图模型中,而不是在后面的代码中。它应该留在那里。
这对绑定类型有影响。要绑定到视图模型的属性,我们使用:
<mstkcontrols:DataGrid ItemsSource="{Binding MyContents}">
但是要绑定到后面代码的一个属性,必须是:
<mstkcontrols:DataGrid ItemsSource="{x:Bind MyContents}">
同时,非常感谢大家阅读和提出建议。我目前正在研究如何连接视图模型和代码。
【问题讨论】: