如何从 UserControl 访问父级的 DataContextUserControl、DataContext

由网友(谁拿流年、乱了浮生)分享简介:我需要从我在 WPF 中创建的 UserControl(包含文本框和列表框的网格:我需要在此列表框中插入项目)访问容器的 DataContext:这是最好的方法吗?I need to access the container's DataContext from a UserControl (a grid conta...

我需要从我在 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.

阅读全文

相关推荐

最新文章