如果WPF控件具有内容变量,将如何检查?
我正在使用此代码迭代所有控件:
public void Translate(Visual myVisual)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(myVisual); i++)
{
// Retrieve child visual at specified index value.
Visual childVisual = (Visual)VisualTreeHelper.GetChild(myVisual, i);
//How can I check wether childVisual has a Content-Variable or hasn't?
//So check if this: childVisual.Content is existing
// Enumerate children of the child visual object.
Translate(childVisual);
}
}
您可以为每个控制类型执行以下操作:
if(visualChild is CheckBox)
//cast it to CheckBox etc.
但那很脏,还有其他可能吗?
答案 0 :(得分:0)
最简单的方法是检查Visual
是否为ContentControl
。通常,具有Content
属性的所有WPF控件都派生自ContentControl
。
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(myVisual); i++)
{
// Retrieve child visual at specified index value.
Visual childVisual = (Visual)VisualTreeHelper.GetChild(myVisual, i);
//How can I check whether childVisual has a Content-Variable or hasn't?
var childContentVisual = childVisual as ContentControl;
if(childContentVisual != null)
{
var content = childContentVisual.Content;
...
}
// Enumerate children of the child visual object.
Translate(childVisual);
}
您还可以使用反射来查看Content属性是否存在,但这样做更慢,更麻烦。