你如何将网格的孩子绑定到列表? [英] How do you bind a grid's children to a list?
问题描述
在我的ViewModel中,我有一个项目列表,我希望我的视图中的网格绑定到这些项目(这些项目将是网格子项)。该列表是这些项目的视图模型列表。
如何将网格绑定到列表(我可以在代码中访问.children而不是xaml)?
另外,如何为列表中的视图模型指定数据模板(另一个xaml文件),以便它们在网格中正确呈现。
谢谢
ItemsControl
和 ItemsPanel
设置为一个Grid: < 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.RowValue ={Binding RowIndex}/>
< Setter Property =Grid.ColumnValue ={Binding ColumnIndex}/>
< / style>
< /ItemsControl.ItemContainerStyle>
In my ViewModel I have a list of items that I would like a grid in my view to bind to (the items will be the grids children). The list is a list of view models for the items.
How do you bind a grid to the list (I can access .children in code but not xaml)? Also, how do you specify the data template (another xaml file) for the view models in the list so that they are rendered correctly within the grid.
Thanks
Use an ItemsControl
with the ItemsPanel
set to a Grid :
<ItemsControl ItemsSource="{Binding TheList}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Grid/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
In the ItemsControl
's ItemContainerStyle
, you might want to bind the Grid.Row
and Grid.Column
attached properties to some property of the items :
<ItemsControl.ItemContainerStyle>
<Style TargetType="{x:Type FrameworkElement}">
<Setter Property="Grid.Row" Value="{Binding RowIndex}"/>
<Setter Property="Grid.Column" Value="{Binding ColumnIndex}"/>
</Style>
</ItemsControl.ItemContainerStyle>
这篇关于你如何将网格的孩子绑定到列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!