简体   繁体   中英

WPF get all Controls “Content”

How would check, if a WPF control has a Content-Variable?

I'm iterating through all of the controls using this Code:

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

You propably coud do the following for every Control-Type:

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

But that's dirty, is there any other possibility?

The easiest way would be to check if your Visual is a ContentControl . Generally, all WPF controls that have a Content property derive from 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);
}

You could also use reflection to see if a Content property exists, but that's slower and more cumbersome.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM