我有一个与查找用户控件的子控件相关的问题。用户控件驻留在选项卡控件的选项卡项中
XAML
<TabControl HorizontalAlignment="Left" Height="100" VerticalAlignment="Top" Width="150">
<TabItem Header="First tab">
<Grid Background="#FFE5E5E5"/>
</TabItem>
<TabItem Header="Tab with stackpanel" x:Name="tabWithStackPanel">
<StackPanel>
<TextBox></TextBox>
<TextBox></TextBox>
<TextBox></TextBox>
<TextBox></TextBox>
<TextBox></TextBox>
<TextBox></TextBox>
<TextBox></TextBox>
</StackPanel>
</TabItem>
<TabItem Header="Tab with user control" x:Name="tabWithUserControl">
<control:UserControl1/>
</TabItem>
</TabControl>
<Button Height="46" Width="70" Panel.ZIndex="1001" Click="Button_Click">Find</Button>
返回依赖对象的子对象的方法
public static List<T> FindChildren<T>(DependencyObject parent) where T : DependencyObject
{
if (parent == null) return null;
List<T> children = new List<T>();
int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < childrenCount; i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
T childType = child as T;
if (childType == null)
{
children.AddRange(FindChildren<T>(child));
}
else
{
children.Add((T)child);
}
}
return children;
}
正如您在 XAML 中看到的那样,第二个 TabItem
包含一个 StackPanel
,其中包含一些 TextBoxes
。第三个 TabItem
包含一个 UserControl
,它还包含 TextBoxes
。
现在,当我单击“查找”按钮时,事件处理程序应执行以下操作
var children1 = Util.FindChildren<TextBox>(tabWithStackPanel.GetValue(TabItem.ContentProperty) as StackPanel);
var children2 = Util.FindChildren<TextBox>(tabWithUserControl.GetValue(TabItem.ContentProperty) as UserControl1);
问题是第一行返回了 StackPanel
面板的所有子项,但第二行没有返回 UserControl1
的所有子项。
我必须先选择“带用户控件的选项卡”才能获得 UserControl1
的所有子项。
知道如何解决这个问题吗?
最佳答案
未选中的 TabItem
不存在于 Visual 树中,但存在于 Logical 树中。
将对 VisualTreeHelper
的调用替换为对 LogicalTreeHelper
的等效调用
关于wpf - 在选项卡项中查找用户控件的子项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16101411/