Monday, August 30, 2010

MVVM (ICommand) in Silverlight

There is no support for commands in Silverlight. When the user manipulates controls in your view you will have to write code that modifies the view-model in the code-behind for your view. This might be something as simple as calling a method on the view-model when the user clicks a button in the view. By using PRISM you are able to create attached properties in the XAML for your view to get rid of these event-handlers, but if you would rather not use PRISM you can simply stick to using event handlers.

One other aspect you will have to handle is modifying the view when the view-model changes. In particular you will want to enable and disable controls based on the state of the view-model. To achieve this you will have to bind the IsEnabled property of a control to something in the view-model that reflects if a certain operation is allowed. Implementing custom IValueConverter objects that converts to boolean values are often useful. For instance, if your view-model has a property that represents a count and you want a particular control in the view to only be enabled when the count is greater than zero you can create a value converter that converts to true when the number is greater than zero and use this value converter in the binding.

If you try to adapt a WPF example of an MVVM application you will have to get rid of all uses of commands and substitute your own code. The code in your example is not meaningful in Silverligt, but in WPF it is involved in the process of determining if a control in the view is enabled, visible etc.

No comments:

Post a Comment