Setting properties in a VM

Topics: Prism v2 - WPF 3.5
Dec 1, 2009 at 3:12 PM


I've been playing with ways to allow a View designer to control (in XAML) the selection of the ViewModel and also to set properties in it.  Here's a simplified example of the approach I took:

<UserControl x:Class="LLNet.Modules.Library.Views.LibraryView2"
                <mr:BaseDragDropTV x:Name="TV" 

In this example 'Layout.ViewModel' is an attached property. In the callback I instantiate the requested VM and set it as the DataContext to the View like this:
public void ResolveViewModel(System.Windows.FrameworkElement f, string viewModelName)

            Type t = Type.GetType(viewModelName);
            f.DataContext = container.Resolve(t);

'mr:BaseDragDropTV' is a TreeView derived class where AllowedActions is again a DependencyProperty whose PropertyChangedCallback fires during the View's InitializeComponent. Here's the callback code:

      static void AllowedActionsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
            BaseDragDropTV bdd = (BaseDragDropTV)d;
            if (bdd.DataContext != null)
                ((ITVVM)bdd.DataContext).AllowedActions = (AllowedActions)e.NewValue;
This works since the ViewModel callback has already fired and the DataContext (i.e. the VM) is already set.  So far so good -
 but now I have a situation where I want to nest this view inside another whilst setting the 't:Layout.ViewModel' in the outer view. Now my pattern falls apart
since the inner view has not yet picked up the DataContext when the AllowedActions callback fires (the View is instantiated via a RegisterViewWithRegion call in
the relevant module.
Is there a way around this.  Or possibly a better approach to the whole scenario (I do have a feeling I've maybe overcomplicated this one)
Dec 2, 2009 at 7:09 PM

There was a far simpler (and more obvious) method of handling this : Using the DataContextChanged event to grab whatever DependencyProperties I'm interested in.