简体   繁体   English

嵌套用户控件的数据上下文

[英]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; 我有一个wpf视图,其中包含一个组合框,该组合框由使用caliburn micro / ninject和mvvm模式的视图模型填充; 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. 显示在堆栈面板中的每个“嵌套”用户控件都有自己的视图模型,这些视图模型由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. 但这需要视图模型中的无参数构造函数,但是我需要能够将参数传递给此视图模型,以便Ninject可以注入诸如EventAggregator之类的对象。

Going around in ciricles as I am fairly new to WPF so any help would be appreciated. 由于我是WPF的新手,所以转而学习,对您有所帮助。

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. 如果您不喜欢WPF应用程序中的代码,那么我想您可以将视图模型绑定到IEventAggregator对象。

XAML: XAML:

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

Codebehind: 代码背后:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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