How to hide/show Stack panel in wpf mvvm How to hide/show Stack panel in wpf mvvm wpf wpf

How to hide/show Stack panel in wpf mvvm


Use a toggle button and bind the visibility of your UserControl using a BooleanToVisibilityConverter:

Define a resource:

<BooleanToVisibilityConverter x:Key="BoolToVisibility" />

The toggle button:

<ToggleButton x:Name="VisibilityToggle>    <Image Source="..." /></ToggleButton>

The user control:

<MyControl Visibility="{Binding IsChecked, ElementName=VisibilityToggle, Converter={StaticResource BoolToVisibility}}" />


Bind the Visibility property to a bool property of the ViewModel, using a BooleanToVisibilityConverter

<Window.Resources>    <BooleanToVisibilityConverter x:Key="visibilityConverter" /></Window.Resources>...<MyUserControl Visibility="{Binding IsMyUserControlVisible, Converter={StaticResource visibilityConverter}}" />

ViewModel:

private bool _isMyUserControlVisible;public bool IsMyUserControlVisible{    get { return _isMyUserControlVisible; }    set    {        _isMyUserControlVisible = value;        OnPropertyChanged("IsMyUserControlVisible");    }}


Say you have a boolean property in your ViewModel that determines whether or not to show the control

public bool DisplayControl { get; set; }

Bind the visibiilty of your StackPanel using a BooleanToVisibiltyConverter

<Window.Resources>   <BooleanToVisibilityConverter x:Key="visibilityConverter" /></Window.Resources>

And your control:

<StackPanel Visibility="{Binding DisplayControl, Converter={StaticResource visibilityConverter}}"/>