【问题标题】:How do you bind a grid's children to a list?如何将网格的子项绑定到列表?
【发布时间】:2009-09-08 18:56:30
【问题描述】:

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

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

谢谢

【问题讨论】:

    标签: wpf mvvm grid bind


    【解决方案1】:

    使用ItemsControl 并将ItemsPanel 设置为网格:

    <ItemsControl ItemsSource="{Binding TheList}">
      <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <Grid/>
        </ItemsPanelTemplate>
      </ItemsControl.ItemsPanel>
    </ItemsControl>
    

    ItemsControlItemContainerStyle 中,您可能希望将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>
    

    【讨论】:

    • 谢谢。如果其他人遇到此 s:SurfaceUserControl.Resources>
    • 如果您知道需要多少行和列,这是一种享受,但是如果您想要尽可能多的行/列怎么办?有没有办法自动生成行/列定义?​​
    猜你喜欢
    • 2016-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-31
    相关资源
    最近更新 更多