#493 – Setting the Visibility of a User Interface Element

You can set the visibility of any element that inherits from UIElement by settings its Visibility property to one of the three values listed below.  Because every child hosted in a panel derives from UIElement, this is how you hide/show child elements in a panel.

Values for Visibility (of type System.Windows.Visibility):

  • Visible – element is displayed
  • Hidden – element is not displayed, but the space where it is located is preserved
  • Collapsed – element is not displayed and space for it is not preserved

Below is an example that lets a user toggle between the three possible values for the Visibility of the middle Label.

    <StackPanel>
        <StackPanel Orientation="Horizontal" Margin="10">
            <Label Content="Snoopy" Margin="3" Background="BurlyWood"/>
            <Label Content="Waldo" Margin="3" Background="Thistle"
                   Visibility="{Binding ElementName=cboVisibility, Path=SelectedValue, Converter={StaticResource cboVisibilityConverter}}"/>
            <Label Content="Dagwood" Margin="3" Background="LightGreen"/>
        </StackPanel>
        <ComboBox Name="cboVisibility" HorizontalAlignment="Center" SelectedIndex="0">
            <ComboBox.Items>
                <ComboBoxItem Content="Visible"/>
                <ComboBoxItem Content="Collapsed"/>
                <ComboBoxItem Content="Hidden"/>
            </ComboBox.Items>
        </ComboBox>
        <Label Content="Select visibility of middle Label" HorizontalAlignment="Center"/>
    </StackPanel>



Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

2 Responses to #493 – Setting the Visibility of a User Interface Element

  1. Pingback: Dew Drop – February 13, 2012 (#1,264) | Alvin Ashcraft's Morning Dew

  2. Pingback: #644 – Disabling and Hiding Controls « 2,000 Things You Should Know About WPF

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: