2010-07-14 38 views
5

WPF相当新...是否有WPF中的网格面板元素的数据模板?

我有我想绑定到网格面板的数据的集合。每个对象都包含其网格行和列,以及填充网格位置的内容。我真的很喜欢我可以在列表框XAML中创建数据模板来创建一个UI,而在它后面的代码中几乎没有任何内容。有没有办法为网格面板元素创建数据模板,并将面板绑定到数据集合?

回答

13

您可以使用ItemsControlGrid作为其面板。这是一个例子。 XAML:

<ItemsControl x:Name="myItems"> 
     <ItemsControl.ItemsPanel> 
      <ItemsPanelTemplate> 
       <Grid> 
        <Grid.ColumnDefinitions> 
         <ColumnDefinition /> 
         <ColumnDefinition /> 
         <ColumnDefinition /> 
        </Grid.ColumnDefinitions> 
        <Grid.RowDefinitions> 
         <RowDefinition /> 
         <RowDefinition /> 
         <RowDefinition /> 
        </Grid.RowDefinitions> 
       </Grid> 
      </ItemsPanelTemplate> 
     </ItemsControl.ItemsPanel> 
     <ItemsControl.ItemTemplate> 
      <DataTemplate> 
       <TextBlock Text="{Binding MyText}" /> 
      </DataTemplate> 
     </ItemsControl.ItemTemplate> 
     <ItemsControl.ItemContainerStyle> 
      <Style> 
       <Style.Setters> 
        <Setter Property="Grid.Row" Value="{Binding MyRow}" /> 
        <Setter Property="Grid.Column" Value="{Binding MyColumn}" /> 
       </Style.Setters> 
      </Style> 
     </ItemsControl.ItemContainerStyle> 
    </ItemsControl> 

代码隐藏(用于测试目的):

public Window1() 
    { 
     InitializeComponent(); 
     myItems.ItemsSource = new[] { 
      new {MyRow = 0, MyColumn = 0, MyText="top left"}, 
      new {MyRow = 1, MyColumn = 1, MyText="middle"}, 
      new {MyRow = 2, MyColumn = 2, MyText="bottom right"} 
     }; 
    } 
+4

如果您有已知数量的行可以显示,但它不会让您显示任意数量的行,具体取决于您有多少数据。 – LJNielsenDk 2013-04-10 15:29:57

+1

我试图从DataTemplate(在模板的根元素)设置行和列,并想知道为什么它不工作。这非常有帮助。谢谢! – qJake 2016-02-09 18:33:32

0

不知道这是否会帮助你,但你为什么不尝试设置一个ItemsControl的ItemsPanel(列表框,ListView控件),以一个统一的网格。就像这样:

<ItemsControl> 
    <ItemsControl.ItemsPanel> 
     <ItemsPanelTemplate> 
      <WrapPanel /> 
     </ItemsPanelTemplate> 
    </ItemsControl.ItemsPanel> 
</ItemsControl> 

它与以前的解决方案类似,只是更加动态一点。