0

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 ?

Wassim AZIRAR
  • 10,823
  • 38
  • 121
  • 174

2 Answers2

1

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);
Kevin Aenmey
  • 13,259
  • 5
  • 46
  • 45
0

You can put the ones you want hidden inside a grid and set the grid as hidden. The other way is to bind your Visibility to a boolean in either your code behind or (hopefully) your view model. You would need a BooleanToVisibility type converter to accomplish this but it lets you hide an unlimited number of controls that are bound to that field. Here is an example of that: Visibility Type Converter

SASS_Shooter
  • 2,186
  • 19
  • 30
  • I updated my question. They are not in the same parent control. – Wassim AZIRAR Jul 11 '12 at 15:49
  • If you create a view model that is bound to each parent control, and include the BooleanToVisibity type converter then you could control that in a single location no matter where the control is located. – SASS_Shooter Jul 11 '12 at 15:51
  • In each control: Visibility="{Binding SomeVisibilityParameterInViewModelOrOnObject, Converter={StaticResource BooleanToVisibilityConverter}" assuming you are binding to a viewmodel or some sort of view controller and have created a resource of type BooleanToVisibilityConverter and given it a key of that name – Charleh Jul 11 '12 at 15:55