首发于 C# .NET
WPF  依赖属性值优先级

WPF 依赖属性值优先级

本文根据官方文档整理,中英文对照

The workings of the Windows Presentation Foundation (WPF) property system affect the value of a dependency property. This article explains how the precedence of different property-based inputs within the WPF property system determines the effective value of a dependency property.

Windows Presentation Foundation (WPF) 属性系统的工作会影响依赖属性的值。 本文说明 WPF 属性系统中基于属性的不同输入的优先级如何确定依赖属性的有效值。

先决条件

本文假定你对依赖属性有基本的了解,并且已阅读 依赖属性概述 。 若要理解本文中的示例,还应当熟悉 Extensible Application Markup Language (XAML) 并知道如何编写 WPF 应用程序。

WPF 属性系统

The WPF property system uses a variety of factors to determine the value of dependency properties, such as real-time property validation, late binding, and property change notifications for related properties. Although the order and logic used to determine dependency property values is complex, learning it can help you avoid unnecessary property settings, and also to figure out why an attempt to set a dependency property didn't result in the expected value.

WPF 属性系统使用各种因素来确定依赖属性的值,例如实时属性验证、后期绑定和相关属性的属性更改通知。 尽管用于确定依赖属性值的顺序和逻辑比较复杂,但了解它有助于避免不必要的属性设置,还可查明设置依赖属性的尝试未生成预期值的原因。

在多个位置设置的依赖属性

以下 XAML 示例演示对按钮 Background 属性进行的三种不同的“设置”操作如何影响其值。

<StackPanel>
    <StackPanel.Resources>
        <ControlTemplate x:Key="ButtonTemplate" TargetType="{x:Type Button}">
            <Border Background="{TemplateBinding Background}" 
                    BorderThickness="{TemplateBinding BorderThickness}" 
                    BorderBrush="{TemplateBinding BorderBrush}">
                <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
            </Border>
        </ControlTemplate>
    </StackPanel.Resources>
    <Button Template="{StaticResource ButtonTemplate}" Background="Red">
        <Button.Style>
            <Style TargetType="{x:Type Button}">
                <Setter Property="Background" Value="Blue"/>
                <Style.Triggers>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter Property="Background" Value="Yellow" />
                    </Trigger>