I’m trying to learn how to separate a view from its associated viewmodel, while making the view have as little or no code-behind as possible.
my control has a textblock when the object is in a display mode, and a textbox when the user wants to edit that field. In both cases, these controls must bind to the same string in the modelview, but only the appropriate one should be displayed depending on the state of the viewmodel. Previously, I’d just modify the panels child to a new element in the codebehind… but as I understand it, I should be trying to make all my changes in XAML for the view.
My viewmodel has a bool denoting if its in display or edit mode. Is there a way to specify use of a different template depending on the value of that bool, but keep it all in XAML?
There is a way to do what you say you’re working on, by using DataTriggers.
First, define a
Stylewhich contains theDataTriggers you want to use. For example, note here two identical styles for aContentControl, each with aDataTriggerpair that performs the opposite of the other:Then, in your main visual tree you would define
ContentControls which use thoseStyles, and assign theDataContextof theWindoworUserControlor whatever to your ViewModel. Something like this:Here is the ViewModel I’m using, note the implementation of INotifyPropertyChanged:
Now, for the purposes of this sample, I simply wired up the two buttons to set the ViewModel value. If you want to use Commanding to wire up buttons, that’s an entirely different topic. It’s worth discussing, but for the sake of simplicity:
Bear in mind that this sample explicitly styles a
ContentControl, and that you’ll have to change the TargetType of your style if you’re working with a type that isn’t descended from that class.