问题
I am trying to loop through child elements of a Tab Control to know what Check Boxes are set to checked or not checked. I have found various answers on SO, but I can't seem to get the code to do what I need. Here is what I have thus far:
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
}
}
Most likely, I am thinking incorrectly about how the VisualTreeHelper class works. I imagine I can keep working though the XAML Code to keep moving into deeper and deeper children of the Tab Control? Currently, my code on my WPF's xaml looks like this:
<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>
So, my understanding is that I have to work from child to child, meaning, use the VisualTreeHelper to get the Children of the Tab Control (select Tab Item), then get the children of the TabItem (select the grid), then get the children of Grid, and then I can finally loop through the children (checkboxes) to get the information I want. If I am mistaken can someone please explain where I am going wrong?
EDIT: Changed Checkbox XAML to the proper code
回答1:
As far as my knowledge goes, there is no need to do what you're doing to get the children from a parent. You can use the LogicalTreeHelper class. It will let you query objects through the GetChildren
method.
Your code should look like this:
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);
}
}
来源:https://stackoverflow.com/questions/39982806/how-to-loop-through-checkboxes-in-a-tabcontrol-using-wpf