How to change the visible property of the text box from the view template (WPF, MVVM)

advertisements

I am a beginner here in WPF and MVVM. I have certain controls on a window in my project. For example, I have a text box in my window. I am using MVVM Pattern and here I want to change the visible property of the text box from the view model. One other thing is that, I want to change the visibility of the text box from the viewmodel based on some conditions.

Well, I googled it and google throws me some suggestions which were all different solutions and I'm in a total confusion.

Guess some one can help me figure this out.

I know this would be a piece of cake for the WPF MVVM Experts, but since I am trying to learn this stuff I require some code as examples.

Thanks


Since this is MVVM, you don't want to change the visibility of the textbox you actually want to disable some option.. Then - whether that option is enabled or disabled should reflect on the visibility of your Textbox.

So basically you want a Property in the ViewModel such as:

public bool CanMyPropertyBeChanged {get; set;}

Which you can change (of course you should probably implement INotifyPropertyChanged if you haven't already)...
And bind the visibility of the Textbox to this property, via a Converter:

<TextBox Visibility="{Binding CanMyPropertyBeChanged, Converter={StaticResource boolToVis}}" />

You can use the built-in BooleanToVisibilityConverter for this:

<BooleanToVisibilityConverter x:Key="boolToVis" />