团结与WPF-通过属性注入将DataContext注入子控件 [英] Unity & WPF - injecting a DataContext via property injection to a child control

查看:174
本文介绍了团结与WPF-通过属性注入将DataContext注入子控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遵循了 Lab49 中Jason Dollinger的MVVM示例,以了解将Unity与MVVM WPF应用程序。我按照他的基本架构构造了一个简单的示例,使用属性注入和Dependency属性将视图模型注入视图。我的示例有一个主窗口,在该窗口的XAML中创建了一个子用户控件。子控件(还有主窗口)具有用于分配视图模型的属性:

I followed Jason Dollinger's MVVM sample from Lab49 to learn the basics of using Unity with an MVVM WPF application. I constructed a simple sample following his basic architecture, using property injection and the Dependency attribute to inject viewmodels into the views. My sample has a main window with a child user control created in the window's XAML. The child control (and the main window, too) has a property for assigning the viewmodel:

[Dependency]
public IChildViewModel VM
{
    set { this.DataContext = value;}
}

我将所有内容都连接到app.xaml.cs中:

I wire everything up in app.xaml.cs:

protected override void OnStartup(StartupEventArgs e)
{
    base.OnStartup(e);

    IUnityContainer container = new UnityContainer();

    container.RegisterType<IWindowViewModel, Window1ViewModel>();
    container.RegisterType<IChildViewModel, UserControl1ViewModel>();

    Window1 window = container.Resolve<Window1>();
    window.Show();
}

主窗口正在注入其视图模型,但未添加子控件。是否有任何直接方法可以使分辨率向下传播到子控件中?为此,我需要进行哪种架构更改?我现在还没有嫁到Unity,所以如果支持这种行为,我可以切换到另一个容器。

The main window is getting its viewmodel injected, but the child control is not. Is there any direct way of getting the resolution to propagate down into child controls? What kind of architectural changes would I need to make to do so? I'm not wedded to Unity at this point, so I can change to another container if this kind of behavior is supported.

推荐答案

如果我将自己的子视图模型合并并作为窗口的视图模型的属性公开,然后将XAML中用户控件的DataContext设置为适当的属性,则可以从子代码中删除依赖关系属性-完全落后。但是,它导致了一种笨拙的窗口视图模型。我对此并不完全满意。我从 PL的答案此相关问题

If I consolodate my child view models to be owned and exposed as properties on the window's viewmodel, and then set the DataContext of the user controls in XAML to the appropriate property, then I can remove the Dependency-attributed property from the child code-behind altogether. It makes for a kind of clunky window viewmodel, though. and I'm not entirely happy with it. I based this approach from PL's answer to this related question.

这篇关于团结与WPF-通过属性注入将DataContext注入子控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆