【问题标题】:WPF DependencyProperty Inheritance - regular DP vs AttachedWPF DependencyProperty 继承 - 常规 DP 与附加
【发布时间】:2018-10-11 00:14:39
【问题描述】:

1) 对于“字体”,依赖属性继承可以开箱即用。 https://wpf.2000things.com/2014/03/31/1040-an-example-of-dependency-property-inheritance/

您可以更改主窗口上的“字体”,它会向下传播到用户控件(没有任何更改在任何子用户控件中都可以正常工作)。

2) 如果您想让 DP 继承对您自己的 DP 起作用,您的 DP 必须是“附加属性”,您可以通过
一种。 FrameworkPropertyMetadataOptions.Inherits
湾。从类订阅到属性继承:MyClass.InheritedValueProperty.AddOwner

http://devcomponents.com/blog/?p=495

“开箱即用”的 DP 怎么会开箱即用地获得 DP 继承,而如果您希望自己的 DP 继承起作用,那么有很多限制(您的 DP 必须是“附加属性”,事情实现(在任何订阅它的类中都有这么多样板代码)?

对于“开箱即用”的 WPF 实现,我假设框架基类 “DependencyObject” 中的那些样板代码?此外,“Font”是框架基类“Control”中定义的DP(甚至MainWindow也是一个Control)-
https://docs.microsoft.com/en-us/dotnet/api/system.windows.controls.control?view=netframework-4.7.2
https://docs.microsoft.com/en-us/dotnet/api/system.windows.window?view=netframework-4.7.2

WPF DepdendencyObject 必须为 Font 等开箱即用的 DP 实现开箱即用的 DP 继承?

【问题讨论】:

标签: c# wpf


【解决方案1】:

您的描述正是它是如何为开箱即用的 WPF 属性(例如 FontFamily)实现的。 FontFamily 被声明为 TextElement 类的附加属性...

public abstract class TextElement : FrameworkContentElement, IAddChild
{

    …

    /// <summary>
    /// DependencyProperty for <see cref="FontFamily" /> property.
    /// </summary>
    [CommonDependencyProperty]
    public static readonly DependencyProperty FontFamilyProperty =
        DependencyProperty.RegisterAttached(
            "FontFamily",
            typeof(FontFamily),
            typeof(TextElement),
            new FrameworkPropertyMetadata(
                SystemFonts.MessageFontFamily,
                FrameworkPropertyMetadataOptions.AffectsMeasure |                 
                FrameworkPropertyMetadataOptions.AffectsRender | 
                FrameworkPropertyMetadataOptions.Inherits),
                new ValidateValueCallback(IsValidFontFamily));

...然后在Control 类中将其添加为所有者...

public class Control : FrameworkElement
{
    …

    /// <summary>
    ///     The DependencyProperty for the FontFamily property.
    ///     Flags:              Can be used in style rules
    ///     Default Value:      System Dialog Font
    /// </summary>
    [CommonDependencyProperty]
    public static readonly DependencyProperty FontFamilyProperty =
            TextElement.FontFamilyProperty.AddOwner(
                    typeof(Control),
                    new FrameworkPropertyMetadata(SystemFonts.MessageFontFamily,
                        FrameworkPropertyMetadataOptions.Inherits));

您必须像 WPF 程序员那样做。

【讨论】:

    猜你喜欢
    • 2014-09-25
    • 2010-10-22
    • 1970-01-01
    • 2013-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-28
    • 1970-01-01
    相关资源
    最近更新 更多