嵌套控件结构 - 在 XAML 还是 C# 中? [英] Nested controls structure - in XAML or C#?
问题描述
我想创建一个由相当多的元素组成的结构,它的基本布局是这样的:
I want to create a structure which consists of quite some elements, the basic layout of it goes like that:
<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>
所以,有这么多控件,我想知道什么解决方案更优雅、更合适:
So, having that many number of controls, I was wondering what solution is more elegant and proper:
所以整个设计都是用XAML完成的,写的有点多,所有的控件都是手动设置的
So the whole design is done in XAML, which is quite some writing, and all the controls are manually setup there
所以只有主要的 UniformGrid 和 9 个较小的 Uniform 网格是使用 XAML 创建的,然后所有其他东西都是动态创建的,用 C# 编写.另外,如果这是选择,那么请告诉我如何从代码端向边框添加子项的方法.至于现在,这是我的主要方式,我想出了这个:
So just the main UniformGrid and the 9 smaller Uniform grids are created using XAML, then all the other stuff is created dynamically, written in C#. Also if this would be the choice, then please show me the way how to add a child to a border from the code side. As for now, this was my main way of going and I came up with that:
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 代码的混合,我还没有想出:)
3: Mixture
Some kind of different mixture of C# and XAML code, which I havent come up with yet :).
推荐答案
都没有.使用 ItemsControl
或它的派生之一:
None of them. Use an ItemsControl
or one of it's derivatives:
<ItemsControl ItemsSource="{Binding SomeCollectionOfViewModel}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<ItemsControl ItemsSource="{Binding SomeCollection}"> <!-- Nested Content -->
...
</DataTemplate>
<ItemsControl.ItemTemplate>
</ItemsControl>
这篇关于嵌套控件结构 - 在 XAML 还是 C# 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!