我正在尝试遍历选项卡控件的子元素,以了解哪些复选框设置为选中或未选中。我在 SO 上找到了各种答案,但我似乎无法获得代码来做我需要的事情。到目前为止,这是我所拥有的:
foreach (System.Windows.Controls.TabItem page in this.MainWindowTabControl.Items)
{
if(VisualTreeHelper.GetChild(page, 0).GetType() == typeof(System.Windows.Controls.Grid))
{
var grid = VisualTreeHelper.GetChild(page, 0);
int gridChildCount = VisualTreeHelper.GetChildrenCount(grid);
for(int i = 0; i < gridChildCount; i++)
{
if(VisualTreeHelper.GetChild(grid, i).GetType() == typeof(CheckBox))
{
CheckBox box = (CheckBox)VisualTreeHelper.GetChild(grid, i);
if (boxer.IsChecked == true)
checkboxes.Add(box);
}
}
//do work
}
}
很可能,我错误地思考了 VisualTreeHelper 类的工作原理。我想我可以通过 XAML 代码继续工作以继续进入选项卡控件的越来越深的子项?目前,我在 WPF 的 xaml 上的代码如下所示:
<TabControl x:Name="MainWindowTabControl" HorizontalAlignment="Left" Height="470"
Margin="0,10,0,0" VerticalAlignment="Top" Width="1384">
<TabItem Header="TabItem">
<Grid Background="#FFE5E5E5" Margin="0,-21,0,0">
<CheckBox Name="testBox" Content="Check Box"
HorizontalAlignment="Left" VerticalAlignment="Top" Margin="1293,50,0,0"/>
</Grid>
</TabItem>
</TabControl>
所以,我的理解是我必须从一个孩子到另一个孩子,意思是,使用 VisualTreeHelper 获取 Tab Control 的 Children(选择 Tab Item),然后获取 TabItem 的孩子(选择网格),然后获取Grid 的子项,然后我终于可以遍历子项(复选框)来获取我想要的信息。如果我弄错了,有人可以解释我哪里出错了吗?
编辑:将 Checkbox XAML 更改为正确的代码