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:
bool
class ViewModel
{
public bool IsMyImageVisible { get; set; }
}
View:
<Window.Resources>
<BooleanToVisibilityConverter x:Key="booleanToVisibility" />
</Window.Resources>
<Image Visibility="{Binding IsMyImageVisible, Converter={StaticResource booleanToVisibility}}" />
Visibility
class ViewModel
{
public Visibility MyImageVisibility { get; set; }
}
View:
<Image Visibility="{Binding MyImageVisibility}" />
Is "method 2" still MVVM compliant ?
When should I use "method 1" ?
EDIT: changed the questions to be less opinion based.
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.
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.
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