wpf - FrameworkElement 的 DataContext 属性不会沿元素树继承

标签 wpf datacontext inheritance frameworkelement

你好 WPF 专业人士至少我希望你们中的一些人读到这个!

DataContext 是 FrameworkElement(所有 WPF 控件的基类)上的属性,并作为 DependencyProperty 实现。这意味着逻辑树中的所有后代元素共享相同的 DataContext。

所以 ContentControl 应该用它的后代元素来做吗?

我有一个场景是不是 这个案子,我想知道这种不当行为的原因是什么?!

如果您对此有所了解,请阅读此线程(不想在这里复制所有内容)问题开始的地方...:

WPF: Can not find the Trigger target 'cc'. The target must appear before any Setters, Triggers

并在 中说出来短话 :我在 ContentControl 中的 DataTemplates 确实有一个死的 DataContext 这意味着没有什么可以绑定(bind)到它,实际上是不可能的......

ContentControl 下方的每个元素都没有在 DataContext 属性中设置任何内容???

最佳答案

DataContext is a property on FrameworkElement (base class for all WPF Controls) and is implemented as a DependencyProperty. That means all the descendant elements in the logical tree share the same DataContext.



它是一个依赖属性这一事实并不意味着继承... DataContext 是这样的, 但只是因为依赖属性具有 FrameworkPropertyMetadataOptions.Inherits在其元数据中标记。

So the ContentControl should do it with its descendant elements right?


ContentControl有点特别:DataContext它的后代(从 DataTemplate 构建的可视化树)实际上是 ContentContentControl .因此,如果您的 ContentControl没有内容,DataContext里面是空的。

关于wpf - FrameworkElement 的 DataContext 属性不会沿元素树继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4480388/

相关文章:

c# - MVVM - 模型与 ViewModel - 将我的代码放在哪里?

wpf - 简单的网格布局问题

c# - .NET 本地化

c# - 如何在 DataContext 略有不同的情况下重用 UserControl?

c++ - "method injection"的这种虚拟继承使用模式是已知范例吗?

javascript - JavaScript:对象继承自Function.prototype

wpf - 将两个 UIElements 作为 CommandParameter 传递

c# - wpf中的ViewModel层次结构

linq-to-sql - 如何获取 LINQ to SQL 实体的 DataContext?

java - 如何扩展在其方法中返回 this 的类