Thursday, August 16, 2012

Silverlight User control events and MVVM

Silverlight User control events and MVVM

Got little confused with MVVM and user control events.

I have a user control in my view. It has two modes i.e. Read and Edit. (TextMode)
(exposed as Dependancy prop.)

<Grid         x:Name="LayoutRoot"         Background="Transparent">                   <controls:MyUserControl                               Mode="{Binding Path=TextMode,Mode=TwoWay}"                              Text="{Binding Path=ReportText,Mode=TwoWay}"                  </controls:MyUserControl>           </Grid> 

When TextMode changes to 'Edit' , i want to add a 'Save' button to the Phone Applicationbar, and when the Save button is clicked want to save the Text from user control. Also i want to disable Save button in the 'Read' view. (ie.when TextMode is 'Read')

What is the right MVVM way to do this? I thought of two ways :

1) I was thinking exposing ModeChanged property on the user control and propagate it to the view, and then add the Save button. (But that goes against MVVM way i.e. having code in code behind).

2) Handling propertychanged of the dependancy property itself, and adding the save button, from the user control. (doesn't seem right as application logic gets mixed in usercontrol)

How do i involve the view model in this?

What is a good way of doing such operations that will follow MVVM.

Answers & Comments...

Answer: 1

The ApplicationBar is not a DependencyObject and therefore cannot be databound. Therefore there is no point in getting hung up about the specifics of MVVM in this regard.

The purpose of MVVM is to separate your business logic from the UI. Therefore MVVM is not about religiously avoiding the code-behind. In fact, one of the dangers is in trying to impose too many responsibilities on the View Model in fear of using the code behind.

One last thing to consider is that breaking the almighty MVVM pattern, if you choose to do so, is only a problem if others must figure out what you have done. Most dev teams will look for code in the code-behind after exhausting all other possibilities (and wasting half an hour or more). However, in the case of the ApplicationBar, there is no other place it could be.

In short, there is nothing wrong with your first option.

Answer by TriggerPin for Silverlight User control events and MVVM




No comments:

Post a Comment

Send us your comment related to the topic mentioned on the blog