在上一节中,我们学习了什么是行为,并给TextBlock文字块开发一个阴影行为,但是那个TextBehavior只能给TextBlock控件使用,我们还可以进一步优化这个行为,使之所有控件都可以直接使用。
这一节,我们来优化一下这个阴影效果。新建一个ShadowBehavior类,并继承Behavior基类,T泛型参数改为UIElement。如下所示:
public class ShadowBehavior : Behavior<UIElement> { private DropShadowEffect effect = new DropShadowEffect(); protected override void OnAttached() { base.OnAttached(); AssociatedObject.MouseEnter += AssociatedObject_MouseEnter; AssociatedObject.MouseLeave += AssociatedObject_MouseLeave; effect.ShadowDepth = 0; effect.BlurRadius = 5; effect.Color = Colors.Black; AssociatedObject.Effect = effect; } //鼠标离开去掉阴影 private void AssociatedObject_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e) { effect.BlurRadius = 5; } //鼠标进入增加阴影 private void AssociatedObject_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e) { effect.BlurRadius = 15; } }
这次我们将代码做了一些优化,比如只实例化了一个DropShadowEffect 对象,更节省内存。同时,由于Effect 属性定义在UIElement基类中,所以T参数就是UIElement。这样做的好处是,所有控件都可以共享这个行为了。比如下面的Border、TextBlock和Button都可以使用这个阴影效果。
<Window x:Class="HelloWorld.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:HelloWorld" xmlns:controls="clr-namespace:HelloWorld.Controls" xmlns:helper="clr-namespace:HelloWorld.MVVM" xmlns:i="http://schemas.microsoft.com/xaml/behaviors" xmlns:behavior="clr-namespace:HelloWorld.Behaviors" mc:Ignorable="d" Background="DarkCyan" Title="WPF中文网 - 行为 - www.wpfsoft.com" Height="350" Width="500"> <Window.DataContext> <local:MainViewModel/> </Window.DataContext> <Canvas> <Border Width="50" Height="50" CornerRadius="50" Background="LightGoldenrodYellow" Canvas.Left="228" Canvas.Top="20"> <i:Interaction.Behaviors> <behavior:ShadowBehavior/> </i:Interaction.Behaviors> </Border> <TextBlock Text="WPF中文网" Foreground="White" FontSize="60" Canvas.Left="92" Canvas.Top="75"> <i:Interaction.Behaviors> <behavior:ShadowBehavior/> </i:Interaction.Behaviors> </TextBlock> <TextBlock Text="Behavior行为之阴影效果" Foreground="White" FontSize="40" Canvas.Left="21" Canvas.Top="182"> <i:Interaction.Behaviors> <behavior:ShadowBehavior/> </i:Interaction.Behaviors> </TextBlock> <Button Content="退出" Width="80" Height="30" FontSize="14" Canvas.Left="375" Canvas.Top="265"> <i:Interaction.Behaviors> <behavior:ShadowBehavior/> </i:Interaction.Behaviors> </Button> </Canvas> </Window>

F5运行调试,鼠标放到任意一个控件上,都将出现阴影效果的变化。
当前课程源码下载:(注明:本站所有源代码请按标题搜索)
文件名:107-《行为之UIElement阴影效果》-源代码
——重庆教主 2023年11月21日
链接:https://pan.baidu.com/s/1yu-q4tUtl0poLVgmcMfgBA
提取码:wpff