2013-05-16 43 views
0

我想用动态网格来构建用户界面。至少我认为一个网格是要走的路。 每个细胞的控制应该是相同的,f.e.一个TextBox动态用户界面行和列

每行可以有不同数量的细胞,我认为有关使用ColumnSpan属性,以使用户界面看起来像

First row, 2 cells 
Second row, 3 cells 
Third row, 1 cell 

每个单元应该是F.E.的一部分ObservableCollection<MyCellClass>并且应该具有诸如,Column,Columnspan,Text的性质。

我知道如何构建动态网格,但我不知道如何通过模板设置单元格的内容以及如何绑定文本框。

也许我的方法不是最好的,你有其他想法来解决我的问题。

回答

2

您可以使用Grid作为ItemsControl的ItemsPanel,并将ItemsSource属性绑定到ObservableCollection。

假设你的细胞类看起来像这样:

public class Cell 
{ 
    public int Column { get; set; } 
    public int ColumnSpan { get; set; } 
    public int Row { get; set; } 
    public int RowSpan { get; set; } 
    public string Text { get; set; } 
} 

的XAML可以写成如下所示:

<ItemsControl ItemsSource="{Binding}"> 
    <ItemsControl.ItemsPanel> 
     <ItemsPanelTemplate> 
      <Grid> 
       <Grid.ColumnDefinitions> 
        <ColumnDefinition/> 
        <ColumnDefinition/> 
        <ColumnDefinition/> 
        <ColumnDefinition/> 
       </Grid.ColumnDefinitions> 
       <Grid.RowDefinitions> 
        <RowDefinition/> 
        <RowDefinition/> 
        <RowDefinition/> 
        <RowDefinition/> 
       </Grid.RowDefinitions> 
      </Grid> 
     </ItemsPanelTemplate> 
    </ItemsControl.ItemsPanel> 
    <ItemsControl.ItemContainerStyle> 
     <Style TargetType="ContentPresenter"> 
      <Setter Property="Grid.Column" Value="{Binding Column}"/> 
      <Setter Property="Grid.ColumnSpan" Value="{Binding ColumnSpan}"/> 
      <Setter Property="Grid.Row" Value="{Binding Row}"/> 
      <Setter Property="Grid.RowSpan" Value="{Binding RowSpan}"/> 
     </Style> 
    </ItemsControl.ItemContainerStyle> 
    <ItemsControl.ItemTemplate> 
     <DataTemplate> 
      <TextBox Text="{Binding Text}"/> 
     </DataTemplate> 
    </ItemsControl.ItemTemplate> 
</ItemsControl> 

的下面的代码段将初始化的ItemsControl的两个单元:

public MainWindow() 
{ 
    InitializeComponent(); 

    var cells = new ObservableCollection<Cell>(); 
    cells.Add(new Cell { Column = 0, Row = 0, ColumnSpan = 1, RowSpan = 1, Text = "Cell 1" }); 
    cells.Add(new Cell { Column = 2, Row = 2, ColumnSpan = 2, RowSpan = 1, Text = "Cell 2" }); 
    DataContext = cells; 
} 
+0

谢谢你这个优雅的解决方案。 –

0

为什么不使用这样的东西?

public class ItemVm 
{ 
    // here you can put your desired properties, 
    // although you won't need something like ColumnsSpan etc. 
} 

至于你的网格,你可以使用下面的属性底层结构(视图模型):

public ObservableCollection<ObservableCollection<ItemVm>> Rows { get; } // just an illustration 

现在你只需要一个ListView(类似什么的),其ItemTemplate又是一个ListView(或相似的东西)。内部ListViewItemTemplate将是ItemVm的可视化表示。

请注意,我正在根据MVVM模式描述一种方法。所以你需要一个视图模型的基类。但是你可以在WWW上找到很多框架。