Wednesday, July 31, 2013

Changing Control Visibility in WPF MVVM Apps

In WPF MVVM applications, you might need to show, hide, or collapse controls based on data from ViewModels. This is trivial for code-behind applications: name the control & manipulate its visibility directly when you need to. MVVM applications need a different approach. In this post, I'll outline two of the approaches that I have used.

If you use a different approach for manipulating Visibility in WPF MVVM apps, let me know!

Approach A - Introduce Visibility Properties to ViewModel

First, add a new property to your ViewModel. The type of this property needs to be System.Windows.Visibility. The setter for this property can be private; the view only needs the property's getter.

Second, bind the new property to the control's Visibility property.

The advantage to this approach is that you don't have to touch your View's code-behind. The disadvantage is that your ViewModel now contains presentation logic, which is bad for separation of concerns.

Approach B - Set Visibility in Code-Behind

Using this approach requires setting x:Name for your control. The idea is that you add code to code-behind that uses ViewModel values to determine the control's visibility.

If visibility does not change during the Page's lifetime, you can go ahead and set Visibility during Page initialization using ViewModel data.

If the visibility of your control can change during the lifetime of the page, you'll need to use messaging or events in your ViewModel to trigger updates to the page. The event handling (or message handling) code will set the Visibility of the control.

The code-behind will be larger (due to the Visibility-setting code and any additional event/message handlers that you add) and your Page will have an additional property (the control), but this allows you to manipulate control visibility without adding presentation-specific code to your ViewModel.

No comments:

Post a Comment