如何通过类型得到一个WPF容器的孩子? [英] How to get children of a WPF container by type?
本文介绍了如何通过类型得到一个WPF容器的孩子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我怎样才能键入组合框
的子控件 myContainer中
电网
在WPF?
<电网X:NAME =myContainer中>
<标签内容=名称NAME =LABEL1/>
<标签内容=国家名称=LABEL2/>
<组合框高度=23的HorizontalAlignment =左NAME =comboBox1/>
<组合框高度=23的HorizontalAlignment =左NAME =comboBox3/>
<组合框高度=23的HorizontalAlignment =左NAME =comboBox4/>
< /网格和GT;
此行给我一个错误:
VAR myCombobox = this.MyContainer.Children.GetType(组合框);
解决方案
这个扩展方法将递归搜索所需类型的子元素:
公共静态牛逼GetChildOfType< T>(此DependencyObject depObj)
其中T:DependencyObject的
{
如果(depObj == NULL)返回NULL; 的for(int i = 0; I< VisualTreeHelper.GetChildrenCount(depObj);我++)
{
VAR孩子= VisualTreeHelper.GetChild(depObj,I); VAR的结果=(孩子一样T)? GetChildOfType< T>(小孩);
如果(结果!= NULL)返回结果;
}
返回null;
}
所以,使用你可以要求 MyContainer.GetChildOfType<组合框方式>()
How can I get the child controls of type ComboBox
in MyContainer
Grid
in WPF?
<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>
This line gives me an error:
var myCombobox = this.MyContainer.Children.GetType(ComboBox);
解决方案
This extension method will search recursively for child elements of the desired type:
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;
}
So using that you can ask for MyContainer.GetChildOfType<ComboBox>()
.
这篇关于如何通过类型得到一个WPF容器的孩子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文