2

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

<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#代码

所以只有主要的 UniformGrid 和 9 个较小的 Uniform 网格是使用 XAML 创建的,然后所有其他的东西都是动态创建的,用 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 代码的某种不同的混合,我还没有想出:)。

4

1 回答 1

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>
于 2013-06-30T16:51:22.843 回答