如何从用户控件访问父级的DataContext [英] How to access parent's DataContext from a UserControl
问题描述
我需要从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
将是继承,只是不要在 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
.
这篇关于如何从用户控件访问父级的DataContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!