我的项目中有一个Templates.xaml
文件,其中包含样式的ResourceDictionary
。
我想将DropShadowEffect
的Direction
绑定到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
,程序运行正常。但是,在调试时,调试器显示绑定错误:
无法找到目标元素的FrameworkElement或FrameworkContentElement。
我错在哪里?我应该如何防止这种错误?
我建议设置一个常量
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>