Sample code for my #mix10 talk online

Update: Seems that not everyone is running on the latest and greatest, which is understandable. To avoid confusion, I added the version of the framework for which these samples are available. In the next few days, I will try to port them to other versions in order to have working samples in WPF3.5, WPF4, SL3 and SL4. Please be patient, thanks!

Update 2: I reconfigured the samples to include all the external assemblies you need to run them (including Microsoft.Practices.Unity.dll, System.Windows.Interactivity and Microsoft.Expression.Interactions.dll)

Update 3: The MVVM Demo 2 (end) now contains the MVVM Light application for Windows Phone 7 that I demoed at TechDays Belgium 2010 in Antwerpen. It features sharing most of the code between the Silverlight 4 application and the Windows Phone 7 application, and creating a new view for the phone application on top of the MainViewModel.

I just saw that the video for my MIX10 session is online already! Impressive work, MIX10 team. I also published the sample code on my web server, so here are the links:

It was a real pleasure and an amazing experience to have this talk and to get all the great feedback! Thanks all for coming, and as usual don’t hesitate to send your feedback!

Laurent

 

Print | posted on Tuesday, March 16, 2010 10:19 AM

Feedback

# re: Sample code for my #mix10 talk online

left by Michael at 3/17/2010 8:35 PM Gravatar
Session was great!! Hope to see more sessions from you in the near future!!

Regards from Austria ;-)

# re: Sample code for my #mix10 talk online

left by William Apken at 3/18/2010 8:13 AM Gravatar
Watched your session and it was great. Cleared so much up for me. I had to watch some parts 3 times. Guess I'm just slow.

I like the way you can use PRISM as a screen manager. At least that is how I take it. I have not used it in my code yet, but after watching a few videos and some blogs. I think it will do for me what I need.

It seems that there is some over lap with MVVM-light.

What is your opinion on PRISM? Is it needed or can MVVM-light do the same task.

Thank you in advance,
William Apken

# re: Sample code for my #mix10 talk online

left by Keith Duncan at 3/19/2010 3:07 AM Gravatar
Hi Laurent, loved the MVVM presentation cleared up a lot of things for me. In you presentation you demoed a messager sample call SynchronizingWindows, could you possibly post the source for that also. Many thanks for your presentation again.

Thanks

Keith

# re: Sample code for my #mix10 talk online

left by Laurent at 3/19/2010 4:59 AM Gravatar
Hi Keith,

Thanks so much for the good words. The SynchWindows demo needs a tiny bit of cleanup (it was actually written with an old version of the messenger), but I will post it ASAP. Stay tuned to the blog, I will put it up there when it is ready in a few days.

Cheers,
Laurent

# re: Sample code for my #mix10 talk online

left by Laurent at 3/19/2010 5:07 AM Gravatar
Hi William,

Prism is great when you need some UI composition features, which it seems like you do. If you do use Prism in your project, then I would rather recommend using Prism (DelegateCommand, EventAggregator) in lieu of MVVM Light (RelayCommand, Messenger).

MVVM Light is lighter and easier to start with; I also think that the API is easier to use than the prism one; but it does not help you with composition.

Another way to do UI composition is to use MVVM Light together with MEF. This is perfect for small composite applications, though it does require more code to compose the regions together. Check Glenn Block's blog for demos with Widgets. This is a cool combination too, though less specialized than Prism is.

I hope this helps you,
Laurent

# re: Sample code for my #mix10 talk online

left by Alexey at 3/19/2010 4:40 PM Gravatar
Hi Laurent,

The session was great, thank you! I really love the approach that subscribing messages and having this kind of constraint means "something wrong".

But there is one thing that cannot make me sleep peacefully.
You know, this RelayCommand<> stuff.. It is great and simple, but I'm really confused with the necessity of having something like "SayHelloCommand.RaiseCanExecuteChanged".
IMO it is much worse compare to that "annoying reference", mostly for two reasons:

1) [small problem] We raise the event externally, it's kinda a hack;
2) [big problem] responsibility. Now *every property* must know if it is a part of any command, which ones exactly, etc. When normally it is up to the command to decide: "OK, *my* state is changed when that and that properties have these values".
You know, we just spread the logic around the whole model, changing this model, these properties, you always have to think and know which commands you have in your system, what these commands do, how they are implemented, should this particular property affect this particular command or not, should you raise the event for this command or not.

Simply, it's not up to props to decide what do they affect, don't you think? That's the whole idea of INotifyPropertyChanged - property just says "hey, hey, look at me, I'm changed, everybody, I'm changed, take this into account, do what you need, I don't know who you all are, but I warn you!". That's what properties say and that's the idea, isn't it?

What do you think about it?

# re: Sample code for my #mix10 talk online

left by Flemming at 3/20/2010 9:53 PM Gravatar
Hi,
Great talk; your MVVM presentation cleared up a lot of things for me (I've toyed with MVVM Light for some time).
The only thing I'm missing at the moment is how the dataservice (WCF) part is organized. Any chance you could post the source for that part as well?
Regards
Flemming

# re: Sample code for my #mix10 talk online

left by Laurent at 3/21/2010 3:33 AM Gravatar
Hi,

This is a very good idea. I will clean that up and post it on my blog. Thanks for suggesting!

The reason why I didn't do this is that it is a WCF service that I use all the time for demos (I used it in my last year's session at MIX too ;) and I just didn't think of publishing the source.

Cheers,
Laurent

# re: Sample code for my #mix10 talk online

left by Laurent at 3/21/2010 7:08 AM Gravatar
Hi Alexey,

You raise valid concerns. Give me a little more time to write a reply, I will get back to you.

Cheers,
Laurent

# re: Sample code for my #mix10 talk online

left by CuriousGeorge at 3/22/2010 10:08 AM Gravatar
Laurent, Great Mix10 talk. It made MVVM much more clear for me. After watching the video I wanted to look through your samples but am finding they have dependencies on Silverlight 4, which I do not have nor want. Is there any chance you could release the samples without that dependency?

# re: Sample code for my #mix10 talk online

left by CuriousGeorge at 3/22/2010 11:05 AM Gravatar
Laurent, I see now that your samples are in fact fully Silverlight. Somehow in watching the video I missed that detail and thought they were WPF apps. So obviously you can't easily decouple the samples from Silverlight without migrating them to WPF.

# re: Sample code for my #mix10 talk online

left by Laurent at 3/22/2010 11:35 AM Gravatar
Hi,

The Messaging sample is WPF 4. The other samples are Silverlight 4. I understand your concerns about not wanting to use the latest version. Porting the samples to WPF3.5, resp. Silverlight 3 is fairly easy but I am not sure yet when I will be able to do it (I am in a bit of a time crunch right now). Stay posted and I will do my best.

Cheers,
Laurent

# re: Sample code for my #mix10 talk online

left by Flemming at 3/22/2010 8:35 PM Gravatar
In the MVVM demo2, you are using UnityContainer.
I've downloaded and installed Unity application block
(beta 2) (and Enterprise Library, as a second try); but I don't find a way to reference the unity assembly.
There must be something else, I need or ... ???

# re: Sample code for my #mix10 talk online

left by Matt at 3/22/2010 8:55 PM Gravatar
Hi Laurent,

Great presentation at MIX. I've been searching for 'best practice' ways to get started with MVVM and your approach to each problem just makes sense. Thanks.
One example that I would love to see is a service that sends messages in a background thread that updates a collection on the UI. The classic example would be a stock ticker - notifying the UI every x seconds of new prices. However, using the MIX samples, having the UI receive a message every few seconds to add a new customer to the Customer collection may be easy to slip in to the current demos. This would help in understanding how to 'subscribe' to a notification-esque service and also adding/removing an item from an ObvservableCollection would be great to see - may also provide a concrete example of the DispatcherHelper - something that wasn't covered at MIX.
Cheers,
Matthew

# re: Sample code for my #mix10 talk online

left by Laurent at 3/22/2010 9:07 PM Gravatar
Hi Flemming,

The version I used is "Unity Application Block 1.2 for Silverlight.msi" which I downloaded from
http://www.microsoft.com/downloads/details.aspx?FamilyID=0991cedb-953a-4367-a2b6-071e31766b4c&displaylang=en

Then, I just picked the assembly in
C:\Program Files\Microsoft Unity Application Block 1.2 for Silverlight\Bin

Hope this helps,
Laurent

# re: Sample code for my #mix10 talk online

left by Laurent at 3/22/2010 9:44 PM Gravatar
Hi Matt,

I got a blog post in preparation regarding DispatcherHelper. The example you mention is pretty trivial to implement using this class, but I agree that a sample is needed. Stay tuned.

Thanks,
Laurent

# re: Sample code for my #mix10 talk online

left by Flemming at 3/23/2010 8:47 PM Gravatar
Follow up on Alexey comment above ...
(I share his concern for RaiseCanExecuteChanged)
For test I loaded your SL RelayCommandDemo and verified RaiseCanExecuteChanged must be implemented.
Next I created the same demo (cut/paste) in a WPF4 application and (surprise) no need for RaiseCanExecuteChanged.
Could this be a bug in RelayCommand for SL or is it somewhere deeper (microsoft)?
/Flemming

# re: Sample code for my #mix10 talk online

left by Laurent at 3/23/2010 9:02 PM Gravatar
Alexey, Flemming,

First, Flemming you are very observant, congrats :) The reason why you don't need to RaiseCanExecuteChanged in WPF is that this platform has a CommandManager class which is observing the UI, and querying CanExecute when the user actuates controls. The CanExecute method is queried very often in WPF. In Silverlight however, the CommandManager class is not there. This is why you need to do it explicitly. For compatibility reasons, the method RaiseCanExecuteChanged is also available in the WPF implementation, but it doesn't do anything.

Regarding the responsibility principle, I tend to agree that this solution is not ideal, because the property is responsible for notifying the Command. Instead, the Command should be responsible for observing the property. This is actually what happens when you implement the ICommand interface yourself, like I show in the ICommand demo. However, because you observe the property (through the PropertyChanged event), you create a strong dependency between the Command and the object that is being observed. In my opinion, this is a losing game, and I prefer to use the RaiseCanExecuteChanged method instead.

I feel that the gain overweighs the loss, since everything remains internal to the view model class.

Note that this is not the only place where this kind of issue arises. You have a similar problem when a property modifies another property. For example, if you have properties FirstName, LastName and FullName: Changing FirstName must raise the PropertyChanged event for FirstName and for FullName. This kind of "cascaded raising" is one of the flaws of the pattern, which I didn't mention at MIX because it is really an advanced concern and I didn't want to confuse people too much. Good that you give me the occasion to write about it here though. That could be a good topic for a blog post.

Thanks a lot guys,
Laurent

# re: Sample code for my #mix10 talk online

left by Alexey Raga at 3/23/2010 10:24 PM Gravatar
Hi Laurent,

Thank you for your response and for your explanation about differences between WPF and Silverlight.

In case of WPF then I totally agree with you: we don't need to raise this event => command can live independently and serve itself once created.

But in case of SL I still disagree. I (almost) don't care how object manages its own state, these properties you mentioned are logically parts of the type.
But the command is a different story as it is an external stuff: logically "here is an object" and "here is a command". And the command object in this case is not self-serviced as an object should be.

Introducing new MyCommand(myObject) instance we don't need to change myObject type and it is one of the main goals and principles of a good design: introducing new functionality without changing existing one (and without even knowing any details of its implementation).

Same for maintainability: as this functionality is not encapsulated, it's not easy to support this logic, to keep the integrity.

But I got your point :)

# re: Sample code for my #mix10 talk online

left by Laurent at 3/23/2010 11:01 PM Gravatar
Hi Alexey,

And I do not disagree with you :)

As I said, the concerns you raise are completely valid. This is a case of one evil against another. In my opinion, RelayCommand is OK because it is exposed as a property of the ViewModel, its context is the ViewModel, and its status changes internally to the ViewModel. But I completely see your point, and agree with you that it is not ideal.

I think that as long as one is aware of the issue, it is OK to go ahead with this implementation. Should that become too big a concern, the alternative is to not use RelayCommand and instead implement the ICommand interface, which will work in SL and WPF. As usual, development is a matter of informed choice. Our task is to teach beginners and let them understand the issue, which is why a separate blog post about this issue seems like a very good idea.

Thanks for the discussion!
Laurent

# re: Sample code for my #mix10 talk online

left by Rob at 3/24/2010 6:10 PM Gravatar
Hi Laurent,
I am really struggling with the ObservableCollection and was hoping you could shed some light. Essentially, I have a collection of Customers. Rather than Add a new Customer to the collection I would like to update an existing Customer (e.g. update their FirstName) and have that update be reflected on my ListView. When I do the update, however, my view does not update. I'm guessing this is because the collection itself did not change but, rather, an item within the collection was modified. Any ideas how I should approach what I was hoping would be a simple task?
Many thanks,
Rob

# re: Sample code for my #mix10 talk online

left by Laurent at 3/24/2010 9:32 PM Gravatar
Hi Rob,

Your problem comes from a common confusion between the ObservableCollection (OC) role and the item's role.

The OC is responsible for notifying the binding that an item has been added, removed or that the sorting order of the items has changed. This is an implementation of the INotifyCollectionChanged interface. The OC is NOT responsible for notifying a binding that the content of an item's property has changed.

On the other hand, the item is responsible for notifying a binding that one of its properties has changed. This is an implementation of the INotifyPropertyChanged interface.

In your item, make sure that the PropertyChanged event is raised when the property changes. Any binding (for example in a DataTemplate) to that particular property will then be updated correctly.

Hopefully this helps,
Laurent

# re: Sample code for my #mix10 talk online

left by Rob at 3/28/2010 1:55 PM Gravatar
Thanks Laurent.. that got me heading in the right direction. Unfortunately I have an ObservableCollection<Customer> and one of the properties within the Customer model is an ObservableCollection<Order>. I implemented INotifyPropertyChanged on this property but this only gets fired when the entire collection is set, not when an Item is added. How do you deal with 'nested' collections?

Thanks again,
Rob

# re: Sample code for my #mix10 talk online

left by Rob at 3/28/2010 4:46 PM Gravatar
I think my issue may also be due to wanting to view readonly properties that relate to information in the collection (e.g. OrdersOverdue) that sit at the Customer level that do not update when the Order collection updates.

public int OrdersOverdue
{
get
{
return Orders.Where(f => f.Due < DateTime.Now).Count();
}

So two issues :)

[1] how to deal with collections that contain items that also have collections.

[2] how to deal with properties that are read-only (so are never 'updated' via a set and therefore don't call RaisePropertyChanged).

# re: Sample code for my #mix10 talk online

left by Laurent at 3/28/2010 7:44 PM Gravatar
Hi,

If a propery does not raise PropertyChanged, the binding will be executed once only. It is what we call a "One Time Binding" (as opposed to One Way and Two Way Bindings).

Nested collections work just like non nested collections. If you want to set this collection as the ItemsSource of a list control (such as ItemsControl, ListBox, DataGrid etc...), then the list control will be updated when the CollectionChanged event is raised (which happens automatically when an item is added, removed or the sorting order changes in the ObservableCollection).

However, if you want the OrdersOverdue property to be databound, and this binding to be updated, you need to raise the PropertyChanged event for that particular property. For example (assuming that myOC is an ObservableCollection):

// Somewhere after the OC is constructed
// Subscribe to CollectionChanged for myOC

myOC.CollectionChanged += (s, e) => RaisePropertyChanged("OrdersOverdue");

This line adds an event handler for the CollectionChanged event, and will raise the PropertyChanged event for the OrdersOverdue property. This way, the bindings will be updated. Note that RaisePropertyChanged is not called from within the Setter of the property (since there are none), but from somewhere else in the class. This works fine.

(note: The PropertyChanged event will also be raised, unnecessary, when the sorting order changes in the collection. To prevent this, you can check the NewItems and OldItems properties on the NotifyCollectionChangedEventArgs class passed to the event).

My advice when you work with nested properties/collections: Be methodic. It all works the same, but it is easy to lose the overview. This is one of these cases where a quick UML diagram/sketch might help to understand what's happening ;)

Cheers,
Laurent

# re: Sample code for my #mix10 talk online

left by Rob at 3/29/2010 9:57 AM Gravatar
Thanks Laurent - I think I understand things much better now. Its funny that you mentioned a diagram as I had just drawn up how I thought the wiring should work on a whiteboard - always makes more sense when you can visualize a problem.

I had originally added RaisePropertyChanged("OrdersOverdue") in the Setter for the Collection but that didn't work.. attaching it to the Event, however did.

Sorry to pull this thread a bit off topic and thanks again for your help.

# re: Sample code for my #mix10 talk online

left by Laurent at 3/29/2010 10:33 AM Gravatar
Hey Rob,

It is normal that the PropertyChanged event is not raised in the Collection's setter: The collection is probably created only once, which raises the propertychanged event only once. ALl subsequent operations (adding/removing items) is done on an already existing collection, thus only the CollectionChanged event is raised. Does that make sense?

Cheers,
Laurent

# re: Sample code for my #mix10 talk online

left by Rob at 3/30/2010 11:55 AM Gravatar
Yeah, it does.

Its all playing nicely now and (I think) it is my first well designed WPF app so I'm quite chuffed.

Again, thanks for your help!

# re: Sample code for my #mix10 talk online

left by Flemming at 4/4/2010 10:56 PM Gravatar
Hi Laurent,
After viewing the video from your MIX10 talk (again), I suddenly realize how usefull Messenger class can be.
Instead of calling methodes on other VM classes, just send a message, and let anybody else do what need to be done. Briliant!
Now I want to dig a little deeper (tokens e.a.).
Anywhere I can find some sample-code?
regards
Flemming

# re: Sample code for my #mix10 talk online

left by Calabonga at 4/5/2010 2:34 PM Gravatar
Thanks! That's realy great presentation! But I can't found a source code of propject. Where can I found it?

# re: Sample code for my #mix10 talk online

left by Laurent at 4/5/2010 7:17 PM Gravatar
Hi,

The source code, as written in the article, is available here:
http://www.galasoft.ch/blogs-all/Resources/MIX10/MIX10-MVVM-Samples.zip

Cheers,
Laurent

# re: Sample code for my #mix10 talk online

left by Matt at 4/7/2010 12:55 PM Gravatar
Hi Laurent,

Was wondering if you could explain how you would implement child / dialog / modal windows using MVVM and the toolkit. Bit lost on where to begin.

Thanks,
Matt

# re: Sample code for my #mix10 talk online

left by Laurent at 4/10/2010 2:33 AM Gravatar
Hey Matt,

My opinion is that *showing* the dialog is the responsibility of the View, while *triggering* the dialog and getting the result is the responsibility of the VM. The way I do it, I have the VM require from the View that the dialog be shown, and then handle a callback to get the result.

Based on this, there are multiple ways to do that. One way I like is to use the Messenger class send a DialogMessage (included in the toolkit) to the View, and then handle a callback to get the dialog's result. However, I would like to rework this part in a future version to make it less dependant on UI information, such as the MessabeBoxResult that it returned. Maybe a better strategy can be to inspire yourself from DialogMessage, and build your own message type.

Other approaches involved a dedicated service used to show dialogs. This is not that different, except that instead of sending messages, you invoke methods on the service.

Hope this helps,
Laurent

# re: Sample code for my #mix10 talk online

left by Flemming at 4/10/2010 8:06 PM Gravatar
Hi,
In one of your MIX10 demos, you was using MS Unity framework; what are the benefits?
/Flemming

# re: Sample code for my #mix10 talk online

left by Laurent at 4/11/2010 3:49 AM Gravatar
Hi,

Unity is an IOC container. I recommend you Google this term with Bing, as there are many many posts explaining the advantages of an IOC container. In short, it helps you to compose multiple loose parts of your application together.

As I said in the MIX10 talk, this is not compulsory at all. In fact I probably would not introduce Unity in an application just to create services and ViewModels. But if (as is often the case in applications nowadays) you already use an IOC container (Unity, StructureMap, NInject etc...), you can also take advantage of it for Services and ViewModels composition.

Hope that helps,
Laurent

# re: Sample code for my #mix10 talk online

left by Laurent at 4/12/2010 12:23 AM Gravatar
Hi Fleming,

Sorry for the long delay in replying.

For the Messenger, check the following articles:

http://blog.galasoft.ch/archive/2009/09/27/mvvm-light-toolkit-messenger-v2-beta.aspx
http://blog.galasoft.ch/archive/2009/10/18/clean-shutdown-in-silverlight-and-wpf-applications.aspx

Also check the "what's new in V3" post
http://blog.galasoft.ch/archive/2010/03/16/whatrsquos-new-in-mvvm-light-v3.aspx


Regarding the usage of tokens, I do not have a sample right now, but the usage is pretty straightforward. Simply use the same token when registering and when sending. The token can be a simple value (which is probably the most logical use) but it can also be an object, in which case you must make sure that you are using the same instance when registering and when sending.

I will write more about this, but I currently don't have much time because I am working on my Silverlight 4 book.

Cheers,
Laurent

# re: Sample code for my #mix10 talk online

left by Jonathan at 4/20/2010 2:07 PM Gravatar
Hi Laurent, your explanation of MVVM was probably the best I've ever seen. It really cleared up a lot of things for me. Thanks!

My question, though, has nothing to do with the topic itself. I saw you used a snippets manager program that allowed you to drag blocks of text onto visual studio, and I wanted to ask what was the name of the program? Is it a feature in VS 2010? It would be useful for me when I'm making presentations too.

Thanks,
Jonathan.

# re: Sample code for my #mix10 talk online

left by Laurent Bugnion at 4/20/2010 8:43 PM Gravatar
Hi Jonathan,

Actually this year I was using the Visual Studio toolbox, in which you can drag (or paste) some text from a text file. Then you can name the snippet as you want (I usually give an index and a short description). To make things clearer, I also add some dummy text snippets that I use as separators between sections of the demo.

About that though: Be super careful, because it happened to me before that suddenly the snippets in the toolbox were lost by Studio. I am very careful to keep a simple text file with all the snippets so that I can open it in last minute and copy/paste from there should that be necessary.

If you want a separate tool, Karen Corby has a WPF-based snippet manager on her blog (http://scorbs.com/2008/03/18/snippetmanager/). It works well too, but on a small screen I prefer the Studio toolbox solution. Karen's manager works with other applications too, though, so it's handy to have.

Cheers,
Laurent

# Mix10.MvvmDemo2 - End

left by Hassan at 5/9/2010 3:46 AM Gravatar
Dear Laurent Bugnion
The session "Mix10.MvvmDemo2 - End" does not open with me the MvvmLight1 project gives me the "project type is not supported by this installation" I have vs 2010 ultimate rc could you help me thnx

# re: Sample code for my #mix10 talk online

left by Hassan at 5/10/2010 3:38 AM Gravatar
Dear Laurent Bugnion Thanks very much to your answer I need to describe for you my problem I work at endowment government organization I decide to use silverlight to our new systems but i can not find any real business sample i need sample like that every user enter the main system gives him his systems links (after login) when he click any system from them it will navigate to it he can return back to the main system and inside any system there is menu not simple but nested after that he can go to any form may be simple or complex form i need simple and master-detail form use mvvm has all functions add, delete, update and has foreign key from another (table) use modal dialog to select it. plz help me if you can thnx alot.

# re: Sample code for my #mix10 talk online

left by Laurent at 5/12/2010 12:15 AM Gravatar
Hi Hassan,

You need the Windows Phone 7 tools to open the MvvmLight1 project. If you do not want to install them, just ignore the warning, you can work with the Silverlight project, but the Windows Phone project will just not load or compile.

Cheers,
Laurent

# re: Sample code for my #mix10 talk online

left by Laurent at 5/12/2010 12:17 AM Gravatar
Hassan, it sounds like you need to look into WCF RIA Services. To combine this with MVVM, check Nikhil Kothari's talk at MIX10
http://live.visitmix.com/MIX10/Sessions/CL09

Enjoy,
Laurent

# re: Sample code for my #mix10 talk online

left by Hassan at 5/12/2010 7:23 AM Gravatar
Dear Laurent Bugnion Thanks very much to your answer but i need master/details form with all function add, delete, edit, print, search, ... i did not find any sample at the internet and also i want to take decision wcf or wcf ria is the best for me thnx again

# re: Sample code for my #mix10 talk online

left by Hassan at 5/21/2010 2:44 AM Gravatar
Dear Laurent Bugnion
I used your template to create simple project it run ok stand alone but when i call this project by using MEF Export at your MainPage and CatalogService.AddXap("MvvmLight1.xap"); at button click it give me this error :
Cannot find a Resource with the Name/Key Locator [Line: 9 Position: 17]
thnx for your answer

# re: Sample code for my #mix10 talk online

left by Manuel at 6/2/2010 2:35 PM Gravatar
Im using GalaSoft.MvvmLight.Messaging;
I have several Messenger.Default.Register<long> in different Viewmodels with the same long -object<TMessage>.
How do i specify that that it will be receive my the specific model since all of the Viewmodel Has registered with the same object.

For instance

Messenger.Default.Register<long>(this,OnDataLoaded) are registerd in TaskViewModel and ProjectViewmodel

and i invoke a send from one of the Views

long id = getid();
Messenger.Send(id);

Im trying to get the specific viemodel(TaskViewmodel) to catch that object. Is there any way to do it or a token to pass?
can you give me a sample code for it. thank you

# re: Sample code for my #mix10 talk online

left by Howard Pinsley at 6/6/2010 4:22 AM Gravatar
Laurent,

Thank you for your excellent presentation. I had a question about your wrapper around the WFC service (Mix10.MvvmDemo1\Model\DataService.cs).

Why do you bother to pass the caller's delegate to the WFC asynch call and then cast it back through UserState as in this snippet?

var userCallback = e.UserState
as Action<IEnumerable<Customer>, Exception>;

if (userCallback == null)
{
return;
}

Isn't the callback variable available to you through a closure in your delegate since it is an argument to your GetCustomers method?

public void GetCustomers(
Action<IEnumerable<Customer>, Exception> callback)

Thanks for inspiring me to look into MVVM!

# re: Sample code for my #mix10 talk online

left by Laurent Bugnion at 6/6/2010 7:46 PM Gravatar
Hi Manuel,

There are two ways to send targeted messages.

1) Send a message to all instances of a given type (or types that implement a given interface):

Messenger.Default.Send<TMessage, TRecipient>(TMessage message) (where TRecipient is a type or an interface)

2) Send a message with a token:

Messenger.Default.Send<TMessage>(TMessage message, object token) (where token can be an object (equality by reference) or a simple value (equality by value). For example, recipient registers with token = 1234, then sender sends with token = 1234, which ensures a point to point communication (if multiple recipients use the same token, they will all get the same message).

Does that make sense?

Cheers,
Laurent

# re: Sample code for my #mix10 talk online

left by Laurent Bugnion at 6/6/2010 7:50 PM Gravatar
Hi Howard,

That's a good question. It is a pattern I am using quite consistently (saving the callback and other needed elements from the request in the UserState). This helps refactoring, typically when a lambda expression grows too big and I decide to move it into its own method.

Also, even though I do use closures too, it sometimes leaves me with a weird feeling.

But to be honest the real reason here is that I didn't think that much and just applied the usual pattern I use with the UserState.

Does that make sense?

Cheers,
Laurent

# re: Sample code for my #mix10 talk online

left by Howard Pinsley at 6/7/2010 2:48 AM Gravatar
Laurent,

Yup. Makes sense. In the end, it is whatever works and is most understandable to you. :-)

Thanks for sharing your expertise with MVVM. I'm starting Silverlight now and want to ensure that I start using good habits. Even though I don't have a designer, MVVM seems to be the best way to embrace SOLID principles.

# re: Sample code for my #mix10 talk online

left by John Goldsmith at 8/11/2010 3:14 AM Gravatar
Hi Laurent,

I'm just trying out your MVVMDemo2 solution and getting a dead web service:
http://www.galasoft.ch/labs/Customers/CustomerService.svc

Is that temporary or have you should we send flowers to the svc?

Thanks

John
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification: