gpt4 book ai didi

c# - 如何按类型获取 WPF 容器的子容器?

转载 作者:IT王子 更新时间:2023-10-29 03:57:03 24 4
gpt4 key购买 nike

如何在 WPF 中的 MyContainer Grid 中获取 ComboBox 类型的子控件?

<Grid x:Name="MyContainer">                    
<Label Content="Name" Name="label1" />
<Label Content="State" Name="label2" />
<ComboBox Height="23" HorizontalAlignment="Left" Name="comboBox1"/>
<ComboBox Height="23" HorizontalAlignment="Left" Name="comboBox3" />
<ComboBox Height="23" HorizontalAlignment="Left" Name="comboBox4" />
</Grid>

这一行给我一个错误:

var myCombobox = this.MyContainer.Children.GetType(ComboBox);

最佳答案

此扩展方法将递归搜索所需类型的子元素:

public static T GetChildOfType<T>(this DependencyObject depObj) 
where T : DependencyObject
{
if (depObj == null) return null;

for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
var child = VisualTreeHelper.GetChild(depObj, i);

var result = (child as T) ?? GetChildOfType<T>(child);
if (result != null) return result;
}
return null;
}

所以使用它你可以请求 MyContainer.GetChildOfType<ComboBox>() .

关于c# - 如何按类型获取 WPF 容器的子容器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10279092/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com