如何将网格的子项绑定到列表?

Dan*_*net 13 wpf grid bind mvvm

在我的ViewModel中,我有一个项目列表,我希望在视图中绑定一个网格(项目将是网格子项).该列表是项目的视图模型列表.

如何将网格绑定到列表(我可以在代码中访问.children但不能访问xaml)?此外,如何为列表中的视图模型指定数据模板(另一个xaml文件),以便在网格中正确呈现它们.

谢谢

Tho*_*que 22

使用ItemsControl带有ItemsPanel网格的集合:

<ItemsControl ItemsSource="{Binding TheList}">
  <ItemsControl.ItemsPanel>
    <ItemsPanelTemplate>
        <Grid/>
    </ItemsPanelTemplate>
  </ItemsControl.ItemsPanel>
</ItemsControl>
Run Code Online (Sandbox Code Playgroud)

ItemsControl's中ItemContainerStyle,您可能希望将Grid.RowGrid.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>
Run Code Online (Sandbox Code Playgroud)