.NET, MVVM, RIA, Silverlight, WCF RIA Services »

[9 Jun 2011 | 0 Comments]

I’ve just finished my session on Silverlight, MVVM and RIA Services – an architectural story at NDC2011.  Almost a full room, thanks for such a great turnout!

 

riaservarch

 

As promised, the slides + democode are available for download.  Any questions on the session or the principles discussed therein?  Drop me a line or contact me on Twitter.

 

Cya around! :-)

.NET, Featured, MVVM, Silverlight »

[28 Jan 2011 | 4 Comments]

Image this: you’re working on a Silverlight application, using the MVVM pattern, and you want to do something with the result of an async request (for example, you’re fetching persons, and you want to add them to a list in your VM when the operation completes).  Something like this:

 

PersonServiceReference.PersonServiceClient client = 
new PersonServiceReference.PersonServiceClient();
          
client.LoadPersonsCompleted += (s, a) =>
{
    if (a.Error == null)
    {
        AllPersons = new ObservableCollection<Person>(a.Result);
     }
};
client.LoadPersonsAsync();

 

However, when you do this, you get an “invalid cross-thread exception” (if AllPersons is bound to a list in your UI).  What does this mean?  Simply put, you’re trying to access the UI thread (as the list you’re manipulating is bound to something in your UI), but you’re doing this from another thread: the thread on which your async operation runs.

 

Luckily, this is pretty easy to solve: invoke the Dispatcher as such and you’ll get rid of above exception:

 

Dispatcher.BeginInvoke(() =>
{
// your code
});

 

Now, if you’re trying this at the moment, and you’re using the MVVV pattern, you’re probably trying this in your VM and you’ve probably noticed something: it doesn’t work.  Why?  It doesn’t work because you don’t have access to the dispatcher: you can only get to it from inside of classes inheriting UI controls (such as UserControl, Page, …).  Quite logical, actually: since it’s used for trying to get back to the UI thread, it’s useless in non-UI-related code.  Operations like that aren’t allowed: for example, try to access the Applications’ RootVisual from inside a VM, and you’ll get an unauthorized access exception.

 

However, in MVVM, we actually DO need access to the Dispatcher.  Luckily, it’s not that hard to do.  The solution I prefer is keeping the dispatcher in a static variable, so it’s accessible from anywhere in your application.  To achieve this, create a class (eg: LocalStateContainer) with a static variable in your application.  In your App Start, fill this variable with the dispatcher:

 

LocalStateContainer.Dispatcher = RootVisual.Dispatcher;

 

Now, you can access it from anywhere in your application to get back to the UI thread when needed. 

 

To get back to our original problem, following code will solve it:

 

PersonServiceReference.PersonServiceClient client = 
new PersonServiceReference.PersonServiceClient();
          
client.LoadPersonsCompleted += (s, a) =>
{
    LocalStateContainer.Dispatcher.BeginInvoke(() => 
    {
        if (a.Error == null)
        {
            AllPersons = new ObservableCollection<Person>(a.Result);
         }
    });
};
client.LoadPersonsAsync();

 

Hope this helps some of you out! :)

WCF RIA Services, .NET, MVVM, General »

[30 Sep 2010 | 0 Comments]

A while ago, Gill Cleeren and I wrote an article for Technet Magazine on Silverlight for Business applications, touching on WCF RIA Services, MVVM, …  If you’re an IT professional and interested in starting Silverlight development in your business, you can check it out here.

 

A few days later, I was interviewed by the same Technet Magazine for Technet Radio.  It’s a 10 minute podcast on the more interesting parts of starting Silverlight development for your business.  So, want to hear me talk on this? Check it out! :-)

BESUG, Silverlight, WCF RIA Services, MVVM, Presentations and sessions »

[4 May 2010 | 0 Comments]

As mentioned in my previous post, my BESUG session on Model-View-ViewModel in Silverlight was recorded.  Well, today, it was posted at Channel 9!

 

For those of you who want to listen to my session, these are the links (att: in Dutch):

 

http://channel9.msdn.com/posts/adebruyn/Demystifying-MVVM--Part-1-Recording-BESUG-session/

http://channel9.msdn.com/posts/adebruyn/Demystifying-MVVM--Part-2-Recording-BESUG-session/

 

Have fun! :)

General, MVVM, Silverlight, WCF RIA Services »

[30 Apr 2010 | 0 Comments]

Thanks to everyone who attended my session on MVVM at BESUG yesterday (and thanks for the nice comments ;-))!  As promised, you can find the slidedeck and code here.

 

Included: Powerpoint slides, completed solution and DB Backup. 

 

What you need to run this: Visual Studio 2010 & Silverlight 4 (which includes WCF RIA Services).  For the database, you’ll need SQL Server 2008. 

 

    1. Restore the DB Backup
    2. Change the connection string in web.config
    3. Build, run & play with the code :-)

Hope to see you guys soon at some other event!  If you’ve got any questions on this, don’t hesitate to contact me.

 

Note: this session was also recorded and it scheduled to appear on Microsoft Chopsticks.  Once it’s been published, I’ll post the link.

Silverlight, WCF RIA Services, MVVM »

[22 Apr 2010 | 4 Comments]

As promised, here is the content from my Demystifying MVVM session @ Techdays Portugal.  For those who weren’t there, there’s a lot of stuff in this demo code:

 

  • MVVM base classes,
  • Connecting VM’s to V, using the Locator pattern
  • Connecting them using MEF
  • Unit Testing
  • MEF & Mocking
  • Command implementations (regular & generic), CommandTriggerAction
  • App wide messaging
  • Auto IsDirty support with WCF RIA Services
  • IDialogService implementation for showing Dialogs the MVVM way (same principle applies for your own navigation, states, animations, …)
  • … and some more stuff.

 

So: have a look at the code, and start MVVM-ing yourself in mintues! ;-)

MVVM, Silverlight »

[26 Feb 2010 | 1 Comments]

One of the more common problems (or rather: challenges :)) you’ll run in to when working with the MVVM design pattern is binding from a DataTemplate of an ItemsControl to a command defined on your ViewModel.  For example: you might have a ListBox filled with items, and you want a button in every ListBox item which, on click, should execute a command (delete the item, for example).

 

When you look around the internet, you’ll find a few possible solutions to this problem.  One “easy” one is to simply define a command in each item of the collection you’re binding the ListBox to: as each ListBox item’s DataContext is exactly one item, each DataContext contains a command, so you can bind to it.  Needless to say, this is not the way to go (do you really want a separate command, or a reference to a common command, in each ListBox item?).

 

Another common solution (and a much better one) is using RelativeSource bindings.  You can find a few posts on that on the Silverlight forum and on CodeProject.  As you might notice while looking for info on that: it used to be a WPF-only feature, but it is now supported in Silverlight.  You can find the MSDN page on it here.

 

While that works, there’s actually a much, much easier solution: Element Binding.

 

Take this piece of code:

 

  1. <ItemsControl ItemsSource="{Binding MenuItems}" Grid.Column="1" >
  2.             <ItemsControl.ItemsPanel>
  3.                 <ItemsPanelTemplate>
  4.                     <StackPanel Orientation="Horizontal"></StackPanel>
  5.                 </ItemsPanelTemplate>
  6.             </ItemsControl.ItemsPanel>
  7.             <ItemsControl.ItemTemplate>
  8.                 <DataTemplate>
  9.                     <Button Width="50" Height="50" Content="{Binding Label}"
  10.                             Margin="15">
  11.                         <ToolTipService.ToolTip>
  12.                             <TextBlock Text="{Binding Description}"></TextBlock>
  13.                         </ToolTipService.ToolTip>
  14.                             <i:Interaction.Triggers>
  15.                                 <i:EventTrigger EventName="Click">
  16.                                     <rdmvvm:CommandTriggerAction
  17.                                         Command="{Binding DataContext.ShowView, ElementName=LayoutRoot}"
  18.                                         CommandParameter="{Binding Uri}" />
  19.                                 </i:EventTrigger>
  20.                         </i:Interaction.Triggers>
  21.                     </Button>
  22.                 </DataTemplate>
  23.             </ItemsControl.ItemTemplate>
  24.         </ItemsControl>

 

This is from a project I’m currently working on: the MenuViewModel defines a command, ShowView, which accepts a parameter (the Uri a button click should navigate to).  The menu consists of a (variable, depending on the profile of who logs in) list of buttons, which is created by binding a list of MenuItems to an ItemsControl defined on the View. 

 

So, how do you get the button click event bound to the command defined on your ViewModel?  All my views have a root Grid, LayoutRoot.  As the Views’ DataContext is the ViewModel, the DataContext of LayoutRoot is that same ViewModel – which contains the defined command.  Through element binding, I can now easily bind the command to my ListBox Item, as you can see in the provided code example.

 

I can’t share the complete code this time (that would require sharing most of the internal libraries for MVVM etc we’re using, and would probably violate numerous NDA’s/intellectual property rights :)), but I hope the code sample I provided helps some of you out. 

 

Happy coding! :)