In a MVVM scenario, I want to show/hide a user control based on a hyper link click or image click. How can this be achieved in XAML?
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");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With