gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 22:16:25 25 4
gpt4 key购买 nike

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

<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>

关于c# - 嵌套控件结构 - 在 XAML 或 C# 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17392546/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com