问题描述
考虑到 FrameworkElement
继承 UIElement
,我什么时候从 UIElement
和 FrameworkElement
派生.谁能举出真实的例子?
When do I derive from UIElement
and FrameworkElement
considering FrameworkElement
inherits UIElement
. Can anyone give real life examples?
推荐答案
这是一个学习 WPF 架构的好页面,这个答案只适用于 WPF.如果您有时间,请查看 UIElement
和 FrameworkElement
部分,以及其余部分.这是链接页面的引述,解释了为什么存在 2 个级别:
This is a good page for learning about WPF Architecture, and this answer only applies to WPF. Check out the UIElement
and FrameworkElement
sections, as well as the rest if you have time. Here's a quote from the linked page explaining why the 2 levels exist:
到本主题的这一点,WPF 的核心"特性——在 PresentationCore 程序集中实现的特性,一直是焦点.在构建 WPF 时,基础部分(如使用 Measure 和Arrange 的布局合同)和框架部分(如网格等特定布局的实现)之间的清晰分离是期望的结果.目标是在堆栈中提供一个低扩展点,允许外部开发者在需要时创建自己的框架.
简而言之,UIElement
知道如何绘制自己(因为它们源自 Visual).他们还可以通过提供像 OnPreviewMouseDown
和 OnMouseDown
,以及 布局系统通过实现Measure
和Arrange
.
In short, UIElement
s know how to draw themselves (because they are derived from Visual). They can also use the routed events system by providing virtual methods like OnPreviewMouseDown
and OnMouseDown
, and part of the layout system by implementing Measure
and Arrange
.
FrameworkElement
通过实现一些在 UIElement
中定义的虚拟方法来扩展布局系统.它们提供了设置布局属性的一致方式,例如Margin
属性和 MinWidth
属性.此外,可以设置样式,并且它们可以参与数据绑定.
FrameworkElement
s extend the layout system by implementing some of the virtual methods defined in UIElement
. They provide a consistent way of setting layout properties, e.g. the Margin
property and the MinWidth
property. Additionally, the can be styled, and they can take part in data binding.
回答您的问题,如果您需要 FrameworkElement
添加的任何额外功能,例如您需要更易于使用的样式、绑定或布局系统,然后从中派生.否则,从 UIElement
派生,因为使用 FrameworkElement
会产生轻微的开销.
In answer to your question, if you need any of the extra abilities that FrameworkElement
add, e.g. you need styles, binding or a layout system that's easier to use, then derive from them. Otherwise, derive from UIElement
as there is a slight overhead from using FrameworkElement
.
此外,您应该查看 Control
类(派生自 FrameworkElement
),因为它们提供了有用的新功能层,例如 模板和Padding
等属性.
Also, you should have a look at the Control
class (derived from FrameworkElement
), as these provide useful new layers of functionality like Templating and properties like Padding
.
熟悉继承层次结构也是一个好主意,您可能希望从其中的其他类派生(尽管可能不会比 Visual
更高).
Familiarising yourself with the inheritance hierarchy is also a good idea, you might want to derive from other classes in it (though probably no higher up the chain than Visual
).
这篇关于WPF/Silverlight 中的 UIElement 与 FrameworkElement的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!