How do I bind the visibility of a button to a bool value in my ViewModel?
<Button Height="50" Width="50" Style="{StaticResource MyButtonStyle}"
Command="{Binding SmallDisp}" CommandParameter="{Binding}" Cursor="Hand"
Visibility="{Binding Path=AdvancedFormat}" />
2 way conversion in c# from boolean to visibility
In View:
In view Model:
You will need to have a property changed event
This is how they use Model-view-viewmodel
But since you want it binded to a boolean, You will need some converter. Another way is to set a boolean outside and when that button is clicked then set the property_advancedFormat to your desired visibility.
There's a third way that doesn't require a converter or a change to your view model: use a style:
I tend to prefer this technique because I use it in a lot of cases where what I'm binding to is not boolean - e.g. displaying an element only if its
DataContext
is not null, or implementing multi-state displays where different layouts appear based on the setting of an enum in the view model.Generally there are two ways to do it, a converter class or a property in the Viewmodel that essentially converts the value for you.
I tend to use the property approach if it is a one off conversion. If you want to reuse it, use the converter. Below, find an example of the converter:
A ViewModel property method would just check the boolean property value, and return a visibility based on that. Be sure to implement INotifyPropertyChanged and call it on both the Boolean and Visibility properties to updated properly.
This can be achieved in a very simple way 1. Write this in the view.
The following is the Boolean property which holds the true/ false value. The following is the code snippet. In my example this property is in UserNote class.
This is the way the IsHide property gets the value.
Assuming
AdvancedFormat
is abool
, you need to declare and use aBooleanToVisibilityConverter
:Note the added
Converter={StaticResource BoolToVis}
.This is a very common pattern when working with MVVM. In theory you could do the conversion yourself on the ViewModel property (i.e. just make the property itself of type
Visibility
) though I would prefer not to do that, since now you are messing with the separation of concerns. An item's visbility should really be up to the View.