WPF数据上下文父/子用户控件 [英] WPF datacontext parent / child usercontrols

查看:169
本文介绍了WPF数据上下文父/子用户控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个WPF应用程序,它由一个包含用户控件的窗口组成,而该用户控件又包含另一个子用户控件。

I have a WPF application that is made up of a window containing a usercontrol which, in turn, contains another child usercontrol.

在第二个用户控件的视图模型中,我有一个SelectedName的dependencyProperty。我希望父控件能够访问此属性并在父控件的文本块中显示SelectedName。

I have a dependencyProperty for a SelectedName in my second usercontrol's viewmodel. I want the parent control to be able to either access this property and display the SelectedName in a textblock in the parent control.

我对如何

似乎可以通过两种方法(如果我正确理解的话)
1.在子控件上添加一个事件,并让其事件气泡向上,并在父级中处理。
2.尝试直接在父控件上的文本块绑定中访问子级的依赖项属性。

There seem to be 2 ways I could go (if I understand this correctly) 1. Add an event on the child control and have the event bubble upwards and get handled in the parent. 2. Try and access the child's dependency property directly in the textblock's binding on the parent control.

对于这两种方式,我都会遇到的问题这就是我如何获取控件(子级或父级)数据上下文或视图模型的句柄的方法。

For either of these ways the thing that I am stuck on is how I get a handle on the control's (either child or parent) datacontext or viewmodel.

这是否表明我正走在错误的轨道上?还是我需要将控件的数据上下文转换为相关的视图模型类型,然后使用该视图模型?还是我需要在两个用户控件之间共享相同的视图模型?

Is this a sign that I am heading off on the wrong track or do I need to cast the control's datacontext to the type of viewmodel in question and then use that? Or do I need to share the same viewmodel across both usercontrols?

对于这种方法的任何反馈,我将不胜感激-任何示例对我来说都是非常有用的发现我有一些满足此父/子控制要求的实例。

I'd be grateful for any feedback on this approach - any examples would be really useful as I'm finding I've got a couple of instances of this parent / child control requirement.

再次感谢您的时间。

推荐答案

用于父控件的视图模型可以将子控件的视图模型作为属性,这样您就可以直接从父控件访问它。

The view model used for the parent control could have the child control's view model as a property, that way you can directly access it from the parent.

public class ParentViewModel
{
    public ChildViewModel child { get; set; }
}

然后在xaml中,假设datacontext设置为ParentViewModel对象,我们可以从ChildViewModel轻松访问属性...

Then in the xaml, assuming the datacontext is set to the ParentViewModel object, we can easily access the properties from the ChildViewModel...

<TextBlock Text="{Binding Path=child.SomeTextProperty}" />

这篇关于WPF数据上下文父/子用户控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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