Child views do not instantiate their 'View-Models' automatically

Topics: Prism v4 - WPF 4
Jul 25, 2012 at 10:19 PM
Edited Jul 26, 2012 at 8:12 AM

I have a WPF application in PRISM architecture.

I have a user-control (view) that has 2 user-controls inside it.

Here is the idea : 

Here is an idea :

The reason why the 'Search user-control' is in its own user-control, is because I plan on reusing it in my application.

The main user-control (black) is called 'MainView' and has 2 user-controls in it: - A user-control that has several textbox control I can filter by, and a 'Search' button - A user-control that has a grid where I display the results

Each of these user-controls (and the parent, "Main View") are 'Views' and have 'View-Models'.

Everything is shown fine, except for the fact that the 'child' user-controls do not create their own 'View-Models' automatically.

In the view-model's classes I have the 'Export' attribute, and in the View's code-behind I have this snippet:

[Import]
FilterFieldsViewModel ViewModel
{          
   
set
   
{
       
this.DataContext = value;
   
}
}

Setting the 'View-Model' does happen for the 'Main View', but not for the child views...

I have a command binded to the 'Search' button of the 'Search User-control', and when the application loads - I get an error in the output window, saying :

BindingExpression path error: 'SearchCommand' property not found on 'object' ''MainWindowViewModel' (HashCode=22047425)'. BindingExpression:Path=SearchCommand; DataItem='MainWindowViewModel' (HashCode=22047425); target element is 'Button' (Name='Search'); target property is 'Command' (type 'ICommand')

For some reason the command from the 'child' user-control tries to bind to the view-model in the main window's view model, because for some reason - the child user-control's view model is not instantiated.

Why is this ?

Developer
Jul 26, 2012 at 12:56 PM
Edited Jul 26, 2012 at 12:57 PM

Hi,

Based on my understanding of your scenario, the reason of these error is that child elements automatically inherit the DataContext of their parent element. The data flows down the visual tree, unless you set their own DataContext which in your case seems to be failing. This is why the Binding searches in the "MainWindowViewModel".

Regarding why your 'child' user-controls' view model is not being set, so far, I couldn't find the cause within the code snippets you provided.  It would be helpful to know how your child user-controls are being instantiated, note that in order to have their dependencies resolved you will have to resolve them through the container.

Also, you could try adding the Public modifier to your ViewModel property.

Regards,

Agustin Adami
http://blogs.southworks.net/aadami

Aug 2, 2012 at 8:20 AM

Thanks for your help !