嵌套控件结构 - 在XAML或C#中?

时间:2013-06-30 16:38:17

标签: c# wpf xaml nested

我想创建一个由相当多的元素组成的结构,它的基本布局就是这样:

<UniformGrid>
  <Border>        // This one is 9x
    <UniformGrid> // This one is 9x, each as a child of the border
      <Border>    // This one is again 9x, so at total 9x9 = 81 of these
        <TextBox> // Same as above, each one as a child of the Border
        .....
        </TextBox>
      </Border>
    </UniformGrid>
</UniformGrid>

所以,拥有那么多控件,我想知道哪种解决方案更优雅和恰当:

1:XAML

所以整个设计都在XAML中完成,这是一些写作,并且所有控件都在那里手动设置

2:C#代码

所以只使用XAML创建主UniformGrid和9个较小的Uniform网格,然后动态创建所有其他东西,用C#编写。此外,如果这是选择,那么请告诉我如何从代码端添加一个孩子到边框。至于现在,这是我的主要方式,我想出了:

    private void InitializeCells()
    {
        for (int i = 1; i <= 9; i++)
        {
            object foundControl = sudokuGrid.FindName("cellBorder" + i.ToString());
            Border foundGridControl = (Border)foundControl;
            for (int j = 1; j <= 9; j++)
            {
                TextBox cell = new TextBox();
                cell.MaxLength = 1;
                cell.FontSize = 30;
                cell.Name = "cell" + j.ToString();
                cell.VerticalContentAlignment = VerticalAlignment.Center;
                cell.HorizontalContentAlignment = HorizontalAlignment.Center;
                // HOW TO ADD CHILDREN????
            }
        }
    }
    private void InitializeCellBorders()
    {
        for (int i = 1; i <= 9; i++)
        {
            object foundControl = sudokuGrid.FindName("block" + i.ToString());
            UniformGrid foundGridControl = (UniformGrid)foundControl;
            for (int j = 1; j <= 9; j++)
            {
                Border cellBorder = new Border();
                cellBorder.Name = "cellBorder" + j.ToString();
                cellBorder.BorderBrush = Brushes.DodgerBlue;
                foundGridControl.Children.Add(cellBorder);
            }
        }
    }

3:混合物

C#和XAML代码的某种不同混合,我还没有提出:)。

1 个答案:

答案 0 :(得分:3)

他们都不是。使用ItemsControl或其中一个衍生物:

<ItemsControl ItemsSource="{Binding SomeCollectionOfViewModel}">
   <ItemsControl.ItemsPanel>
      <ItemsPanelTemplate>
         <UniformGrid/>
      </ItemsPanelTemplate>
   </ItemsControl.ItemsPanel>
   <ItemsControl.ItemTemplate>
       <DataTemplate>
          <ItemsControl ItemsSource="{Binding SomeCollection}">   <!-- Nested Content -->
              ...
       </DataTemplate>
   <ItemsControl.ItemTemplate>
</ItemsControl>