【发布时间】:2009-09-08 18:56:30
【问题描述】:
在我的 ViewModel 中,我有一个项目列表,我希望视图中的网格绑定到这些项目(这些项目将是网格子项)。该列表是项目的视图模型列表。
如何将网格绑定到列表(我可以在代码中访问 .children,但不能访问 xaml)? 另外,如何为列表中的视图模型指定数据模板(另一个 xaml 文件),以便它们在网格中正确呈现。
谢谢
【问题讨论】:
在我的 ViewModel 中,我有一个项目列表,我希望视图中的网格绑定到这些项目(这些项目将是网格子项)。该列表是项目的视图模型列表。
如何将网格绑定到列表(我可以在代码中访问 .children,但不能访问 xaml)? 另外,如何为列表中的视图模型指定数据模板(另一个 xaml 文件),以便它们在网格中正确呈现。
谢谢
【问题讨论】:
使用ItemsControl 并将ItemsPanel 设置为网格:
<ItemsControl ItemsSource="{Binding TheList}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Grid/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
在ItemsControl 的ItemContainerStyle 中,您可能希望将Grid.Row 和Grid.Column 附加属性绑定到项目的某些属性:
<ItemsControl.ItemContainerStyle>
<Style TargetType="{x:Type FrameworkElement}">
<Setter Property="Grid.Row" Value="{Binding RowIndex}"/>
<Setter Property="Grid.Column" Value="{Binding ColumnIndex}"/>
</Style>
</ItemsControl.ItemContainerStyle>
【讨论】: