Bind visibility property to a variable

7zawel picture 7zawel · Feb 4, 2013 · Viewed 86.5k times · Source

I have a Border with Label inside a Window,

<Border x:Name="Border1" BorderBrush="Black" BorderThickness="1" HorizontalAlignment="Left" Height="21" Margin="229,164,0,0" VerticalAlignment="Top" Width="90" Opacity="0.5">
    <Grid>
        <Label Content="test"/>
    </Grid>
</Border>

I have also a Variable:

public bool vis = false;

How could I bind the vis variable with border Visibility property?

Answer

Ladislav Ondris picture Ladislav Ondris · May 20, 2016

You don't need to make any converter.

Add a binding to a Visibility property for the border:

<Border x:Name="Border1" Visibility="{Binding Visibility}"    BorderBrush="Black" BorderThickness="1" HorizontalAlignment="Left" Height="21" Margin="229,164,0,0" VerticalAlignment="Top" Width="90" Opacity="0.5">
    <Grid>
        <Label Content="test"/>
    </Grid>
</Border>

And then create the property Visibility in a viewmodel like this:

private Visibility visibility;
public Visibility Visibility
    {
        get
        {
            return visibility;
        }
        set
        {
            visibility = value;

            OnPropertyChanged("Visibility");
        }
    }

So, now you can set Visible or Hidden to your Visibility property as follow:

Visibility = Visibility.Visible;
// or
Visibility = Visibility.Hidden;

But remember, Visibility enum is located in System.Windows namespace, so your viewmodel has to contain using System.Windows;.