嵌套控件结构 - 使用 XAML 还是 C#?

2024-05-11

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

<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 代码混合体,我还没有想出:)。


没有一个。使用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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

嵌套控件结构 - 使用 XAML 还是 C#? 的相关文章

随机推荐