如何使用WPF循环遍历选项卡控件中的复选框
本文关键字:控件 复选框 选项 何使用 WPF 循环 遍历 | 更新日期: 2023-09-27 18:12:48
我试图通过Tab控件的子元素循环,以了解哪些复选框被设置为选中或未选中。我在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来获得选项卡控件的子控件(选择选项卡项),然后获得TabItem的子控件(选择网格),然后获得grid的子控件,然后我最终可以循环遍历子控件(复选框)以获得我想要的信息。如果我错了,有人能解释一下我错在哪里吗?
编辑:将复选框XAML更改为正确的代码
就我所知,没有必要像你现在这样从父母那里得到孩子。您可以使用LogicalTreeHelper类。它将允许您通过GetChildren
方法查询对象。
你的代码应该像这样:
XAML:
<TabControl x:Name="MainWindowTabControl" HorizontalAlignment="Left"
Margin="0,10,0,0" VerticalAlignment="Top" Height="181" Width="247">
<TabItem Header="TabItem">
<Grid Background="#FFE5E5E5" Margin="0,-21,0,0" x:Name="gridChk">
<CheckBox x:Name="testBox" Content="Check Box"
HorizontalAlignment="Left" VerticalAlignment="Top" Margin="0,50,0,0"/>
</Grid>
</TabItem>
</TabControl>
c# :
List<CheckBox> boxesList = new List<CheckBox>();
//The named Grid, and not TabControl
var children = LogicalTreeHelper.GetChildren(gridChk);
//Loop through each child
foreach (var item in children)
{
var chkCast = item as CheckBox;
//Check if the CheckBox object is checked
if (chkCast.IsChecked == true)
{
boxesList.Add(chkCast);
}
}