PilotBob
PilotBob

Reputation: 3117

How can I build UI on the fly in my view model

I have wholly adopted the MVVM pattern for our silverlight app. However, some of our UI is data driven. Mainly two items...

  1. The menu. We are using Infragistics XamMenu.

  2. We have a "dashboard" which allows users to add "snap-ins". This is sort of like a portal site such as iGoogle.

In both cases above the UI needs to be built at runtime. Currently I am running the code in the code behind because I don't see an easy way to access the UI tree in the ViewModel.

In order to run the code in the view I have created an event in the ViewModel that fires once the data is loaded. So, I have to kludge a reference to the viewmodel in the view code behind. I don't like it an it is very ugly... so basically two question:

  1. How can I have the view get a message from the viewmodel that the data is loaded without getting a direct reference to the viewmodel in the view code behind? Currently I pull the reference from the data context.

  2. Is it possible to build the UI in the view model and use data binding. I was wondering if I could bind the "content" of a contentcontrol to some type (not sure what the type would be) in the viewmodel? Of course, the bad part about this is the testability of the view model seems to go away. Can binding be used this way?

Upvotes: 3

Views: 326

Answers (1)

Madeleine
Madeleine

Reputation: 2182

To answer question 1, why dont you make use of the MVVM light "Messenger" class.

In your view,you register to listen to a message in the following way:

Messenger.Default.Register<bool>(this, "MessageId", DoSomething);

Where DoSomething is a method that takes in a boolean parameter (for example).

Then, to send the message from your view model, you do the following:

 Messenger.Default.Send(false, "MessageId");

Hope that helps :) You'll need to add this to your usings:

using GalaSoft.MvvmLight.Messaging;

Upvotes: 2

Related Questions