Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Property of type Visibility in a ViewModel

Tags:

c#

mvvm

wpf

xaml

In a WPF application, when you need to trigger the visibility of an element of the View from the ViewModel, there are basically two methods:

Method 1 : using a bool

class ViewModel
{
    public bool IsMyImageVisible { get; set; }
}

View:

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

<Image Visibility="{Binding IsMyImageVisible, Converter={StaticResource booleanToVisibility}}" />

Method 2 : using a Visibility

class ViewModel
{
    public Visibility MyImageVisibility { get; set; }
}

View:

<Image Visibility="{Binding MyImageVisibility}" />

Questions

  1. Is "method 2" still MVVM compliant ?

  2. When should I use "method 1" ?

EDIT: changed the questions to be less opinion based.

like image 806
Benoit Blanchon Avatar asked Dec 02 '22 21:12

Benoit Blanchon


2 Answers

The second option binds your ViewModel to a specific technology (WPF). Another technology like some web framework will have a different Visibility enumeration. You also might need to add the WPF reference to your model project which might not be a good idea for some scenarios (since all consumers of that project will now have to include that reference as well).

If you do not need cross-framework compatibility in your ViewModel, then you can use the second one without any other drawbacks.

like image 78
Knaģis Avatar answered Dec 05 '22 10:12

Knaģis


Consider the following scenario:

The following interface design decision is made: Instead of hiding the image, it will be made %10 opaque, like a ghost. Now, if you took the second option, you would have to change your viewmodel code because of an interface design change. However, if you took the first option, then you modify the interface (perhaps add an BoolToOpacity Converter) to reflect that change. The first option is more in keeping with MVVM philosophy. And if you have seperate people working on interface design and viewmodel code, then they would not have to interfere in each other's work.

like image 21
Boluc Papuccuoglu Avatar answered Dec 05 '22 10:12

Boluc Papuccuoglu