Silverlight 4 Simple Project Part 4 (Binding & Command)

Silverlight 4 Simple Project Part 3 (MVVM Pattern)

This is the last part of the blog (finally :P).

In the previous post we already created our MVVM. How do we connect our View to the ViewModel? Easy! There are couple of ways to do this. We can do it declaratively in XAML or we can do it in the code-behind.


View - View Model & Binding

I will choose the first option.



Looking at the XAML snippet above, we declare our ViewModel as a User Control Resource and set the DataContext of our main grid to that resource.

Having done that, now we can easily do our data binding for our user elements.



How cool is that? We don't need any code-behind at all for our XAML! This is the beauty of MVVM Pattern.

Now when we select our book title, chapter, or verse, we will get our results back in the grid without any postback since all calls are made asynchronously.



Command

Another new feature in Silverlight 4 is the built-in Commanding option. In this project, if you look at the image above, there is an 'Enable Range' button. I attached a command to this check box so that when IsChecked is True, it will enable the SelectBookVerseEnd selection. If IsChecked is False, it will disable the combobox.

The SelectBookVerseEnd property will in turn decide whether we call the GetAlkitabSnippet function (single AlkitabSnippet object) or the GetAlkitabSnippets function (multiple AlkitabSnippet objects).



Notice that I use UI Element to Element binding between the IsEnabled property of the combobox and the IsChecked property of the checkbox.

To make the commanding easier, I am using the DelegateCommand class (put this inside your ViewModel) that implements the ICommand interface. This class will have the Action and CanExecute parameters that are required by the interface.



If you look at the XAML, the command of the checkbox is bound to DisableRangeCommand.
Lets look at how the commanding is implemented in our view model




and that's it! Simple is that. Commanding enables MVVM pattern since we don't require to handle the UI event in the XAML code behind.

I will post the solution later on. Thanks for reading this and I hope you will find it useful for your own purposes.



Regards,

Andreas

Comments

  1. Hi Andreas,

    Just wondering where can I find the code for this post?

    ReplyDelete
  2. Hii..i am looking how to bind datagrid ,which is inside Silverlight UserControl .please help me.

    ReplyDelete

Post a Comment

Popular posts from this blog

SharePoint 2013 anonymous access add attachments to list item

CRM Plugin - Parent and Child Pipeline

Sitecore custom publish agent from specific node and at a specific time