简体   繁体   中英

Datacontext of nested user controls

Background :-

I have a wpf view containing a combobox which gets populated by the view model using caliburn micro / ninject and mvvm pattern; this view also contains a stackpanel area. When the user selects the appropriate option from the combobox I insert the appropriate user control into the stackpanel presenting the user with a seemless transition to the related display.

Each "nested" user control which gets displayed in the stackpanel has it's own view model automatically associated by caliburn micro.

Problem :-

The "nested" user control bindings all try and refer back to the parent view model and not the view model associated with them specifically.

I can, initially, work around this by specifying :-

<UserControl.DataContext>
    <vm:UserControlSpecificViewModel/>
</UserControl.DataContext>

but this requires a parameterless constructor in the view model but I need to be able to have paremeters passed to this view model so that Ninject can inject objects such as EventAggregator.

Going around in ciricles as I am fairly new to WPF so any help would be appreciated.

Thanks.

James.

One way to solve your problem could be to just initialize your view model in code behind and call the appropriate constructor. If you have a dislike of code behind in your WPF applications then I suppose you could possibly just bind your view model to the IEventAggregator object.

XAML:

<UserControl1 x:Name="myUserControl">
</UserControl>

Codebehind:

public MainWindow() // Constructor for window
{
    InitializeContext();
    MyViewModel vm = new MyViewModel(...);
    myUserControl.DataContext = vm;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM