如何从 UserControl 访问父级的 DataContext [英] How to access parent's DataContext from a UserControl

查看:18
本文介绍了如何从 UserControl 访问父级的 DataContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从我在 WPF 中创建的 UserControl(包含文本框和列表框的网格:我需要在此列表框中插入项目)访问容器的 DataContext:这是最好的方法吗?

I need to access the container's DataContext from a UserControl (a grid containing textboxes and a listbox: I need to insert items in this list box) that I created in WPF: which is the best way to do it?

我正在考虑将 DataContext 作为参数传递给用户控件,但认为有一种更简洁的方法.

I was thinking to pass the DataContext as parameter to user control but think there is a cleaner way to do it.

推荐答案

通常 DataContext 将是 inherited,只是不要在 UserControl 上显式设置它,它将从其父级获取.如果您必须设置它,您仍然可以使用 Parent 属性来获取父级,然后您可以将其安全转换为 FrameworkElement,如果它不为 null,则可以获取其 DataContext.

Normally the DataContext will be inherited, just do not explicitly set it on the UserControl and it will get it from its parent. If you have to set it you could still use the Parent property to get the parent, which you then can safe-cast to a FrameworkElement and if it is not null you can grab its DataContext.

这篇关于如何从 UserControl 访问父级的 DataContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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