绑定到 ResourceDictionary 中的 属性

Bind to a property in a ResourceDictionary

我的项目中有一个 Templates.xaml 文件,其中包含 ResourceDictionary 样式。

我想将 DropShadowEffectDirection 绑定到 MyNamespace.MyPage.LightDirection。目前我这样做了:

// MyPage.xaml.cs
/// <summary>
/// Direction of light source for shadows and gradients.
/// </summary>
public static double LightDirection => 45;
<!--Templates.xaml-->
<Style x:Key="ControlButtons" TargetType="{x:Type Button}">
    <Setter Property="Effect">
        <Setter.Value>
            <DropShadowEffect ShadowDepth="4" Direction="{Binding LightDirection}" Color="Black" Opacity="0.5" BlurRadius="4" />
        </Setter.Value>
    </Setter>
    <!--Other Setters-->
</Style>
<!--MyPage.xaml-->
<Page x:Name="MyPage"
      DataContext="{Binding ElementName=MyPage}">
      <!--MyPage as some other default attributes which I didn't write here-->
    <Grid>
        <Button x:Name="MyButton" Style="{StaticResource ControlButtons}">
            My Button
        </Button>
    </Grid>
</Page>

有效。阴影方向设置为LightDirection,程序正常运行。但是,在调试时,调试器显示绑定错误:

Cannot find governing FrameworkElement or FrameworkContentElement for target element.

我的错误是什么?我应该如何防止这个错误?

我建议做一个常量

namespace MyNamespace
{
    public class Constants
    {
        public static double LightDirection { get; set; }
    }
}

XAML

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"                
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:MyNamespace">
    <Style x:Key="ControlButtons" TargetType="{x:Type Button}">
        <Setter Property="Effect">
            <Setter.Value>
                <DropShadowEffect ShadowDepth="4"
                                  Direction="{x:Static local:Constants.LightDirection}"
                                  Color="Black"
                                  Opacity="0.5" 
                                  BlurRadius="4" />
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

或者直接在XAML

中声明常量
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"                
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:MyNamespace"
                    xmlns:sys="clr-namespace:System;assembly=mscorlib" >
    <sys:Double x:Key="LightDirection">45.0</sys:Double>
    <Style x:Key="ControlButtons" TargetType="{x:Type Button}">
        <Setter Property="Effect">
            <Setter.Value>
                <DropShadowEffect ShadowDepth="4"
                                  Direction="{StaticResource LightDirection}"
                                  Color="Black"
                                  Opacity="0.5" 
                                  BlurRadius="4" />
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>