如何在WPF XAML中将Storyboard.TargetProperty设置为DropShadowEffect或BitmapEffect?
我正在学习C#和XAML,但我不知道如何使用它。另外,如果有人知道可以添加到Storyboard.TargetProperty的属性,请列出它们。
我有这段代码,我从ChatGPT和它的工作,但我需要一个XAML和C#的组合;
using System;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Effects;
using System.Windows.Media.Animation;
using System.Windows.Input;
namespace WpfApp3
{
public partial class MainWindow : Window
{
private DropShadowEffect shadowEffect;
public MainWindow()
{
InitializeComponent();
shadowEffect = new DropShadowEffect
{
ShadowDepth = 10,
Color = Colors.Black,
Opacity = 0,
BlurRadius =10,
Direction = 270
};
button.Effect = shadowEffect;
button.MouseEnter += Button_MouseEnter;
button.MouseLeave += Button_MouseLeave;
}
private void Button_MouseEnter(object sender, MouseEventArgs e)
{
AnimateShadowOpacity(0.5);
}
private void Button_MouseLeave(object sender, MouseEventArgs e)
{
AnimateShadowOpacity(0);
}
private void AnimateShadowOpacity(double targetOpacity)
{
DoubleAnimation animation = new DoubleAnimation
{
To = targetOpacity,
Duration = TimeSpan.FromMilliseconds(250)
};
Storyboard storyboard = new Storyboard();
storyboard.Children.Add(animation);
Storyboard.SetTargetProperty(animation, new PropertyPath("(UIElement.Effect).(DropShadowEffect.Opacity)"));
Storyboard.SetTarget(animation, button);
storyboard.Begin();
}
}
}
这是XAML代码
<Window x:Class="WpfApp3.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp3"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.Resources>
<Style TargetType="Button">
<Setter Property="Height" Value="80"></Setter>
<Setter Property="Width" Value="80"></Setter>
<Setter Property="Background" Value="LightGray"></Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border Background="{TemplateBinding Background}" CornerRadius="18"></Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid>
<Button x:Name="button" Content="Button" MouseEnter="Button_MouseEnter" MouseLeave="Button_MouseLeave"></Button>
</Grid>
</Window>
1条答案
按热度按时间bpsygsoo1#
下面是一个等效的仅XAML解决方案,它还将缺少的
ContentPresenter
添加到Button的Template
中:替代触发器: