WPF获取所有控件“内容”

本文关键字:内容 控件 获取 WPF | 更新日期: 2023-09-27 18:04:19

如果WPF控件有Content-Variable,该如何检查?

我使用以下代码遍历所有控件:

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);
    }
}

您可能可以对每个Control-Type执行以下操作:

if(visualChild is CheckBox)
     //cast it to CheckBox etc.

但那太脏了,还有其他可能吗?

WPF获取所有控件“内容”

最简单的方法是检查您的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属性是否存在,但这更慢,更麻烦。