Templates.xaml我的專案中有一個包含ResourceDictionary樣式的檔案。
我想系結Direction一個DropShadowEffectto 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。
我的錯誤是什么?我應該如何防止這個錯誤?
uj5u.com熱心網友回復:
我建議做一個常數
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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/344994.html
上一篇:為什么WPF畫布會導致System.InvalidOperationException?
下一篇:設定顯示對話框設定圖示
