How to change a WPF control's visibility from ViewModel

Raj picture Raj · Sep 12, 2009 · Viewed 25.1k times · Source

I've an WPF application where tried to implement MVVM pattern and Prism 2. I have a Usercontrol which has subscribed to an event fired from another Usercontrol. I would like to toggle visibility of few child elements in the subscribing control. Events are fired properly, even I am successfully able to bind data to some elements. How do I bind Visibility or any style property for that matter with the ViewModel and change them dynamically.

Answer

Ezequiel Jadib picture Ezequiel Jadib · Sep 12, 2009

You can have a boolean property in your ViewModel and bind that property to the Visibility property of your controls. Since you will be asigning a boolean value and the Visibility property is expecting a Visibility enumeration value, you will have to use the BooleanToVisibilityConverter converter to make the conversion,

<Style.Resources>
     <BooleanToVisibilityConverter x:Key="booleanToVisibilityConverter" />
</Style.Resources>

<Image Visibility="{Binding Path=ShowImage, 
                    Converter={StaticResource booleanToVisibilityConverter}}"/>

Hope this helps.

Ezequiel Jadib