Search code examples
c#wpfxamlmvvmpixelsense

Hide all the controls except one


Suppose that I have this XAML code :

<StackPanel>
    <s:SurfaceTextBox Name="A" />
    <s:SurfaceTextBox Name="B" />
</StackPanel>

<s:ScatterView>
    <s:SurfaceTextBox Name="C" />
    <s:SurfaceTextBox Name="D" />
</s:ScatterView>

How can I hide all those TextBoxes in the code behind, exept the one nammed A.

I'm not asking for this response :

B.Visibility = Visibility.Hidden;
C.Visibility = Visibility.Hidden;
D.Visibility = Visibility.Hidden;

I want something generic which can do it for all, without knowing their names ?


Solution

  • You could probably do something like this:

    public void SetVisibility(UIElement parent)
    {
        var childNumber = VisualTreeHelper.GetChildrenCount(parent);
    
        for (var i = 0; i <= childNumber - 1; i++)
        {
            var uiElement = VisualTreeHelper.GetChild(parent, i) as UIElement;
            var surfaceTextBox = uiElement as SurfaceTextBox;
    
            // Set your criteria here
            if (surfaceTextBox != null && surfaceTextBox.Name != "A")
            {
                uiElement.Visibility = Visibility.Collapsed;
            }
    
            if (uiElement != null && VisualTreeHelper.GetChildrenCount(uiElement) > 0)
            {
                SetVisibility(uiElement);
            }
        }
    }
    

    Give your root element a name:

    <Grid x:Name="Root">
        <StackPanel>
            <s:SurfaceTextBox Name="A" />
            <s:SurfaceTextBox Name="B" />
        </StackPanel>
    
        <s:ScatterView>
            <s:SurfaceTextBox Name="C" />
            <s:SurfaceTextBox Name="D" />
        </s:ScatterView>
    </Grid>
    

    and then call it like this:

    SetVisibility(Root);