行为
行为的用法有些类似触发器的效果,但是触发器一般只能适用同一种的控件;而一个行为可以用在不同控件下(指定相同的父类);
下面实现鼠标移入指定控件的时候发生高亮显示:
namespace MyWpf.CommonService { /// <summary> /// FrameworkElement的派生类下的控件元素都会触发这个行为 /// </summary> public class EffectBehavior : Behavior<FrameworkElement> { protected override void OnAttached() { base.OnAttached(); //关联鼠标移入移出的事件 AssociatedObject.MouseMove += AssociatedObject_MouseMove; AssociatedObject.MouseLeave += AssociatedObject_MouseLeave; } /// <summary> /// 鼠标移出事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void AssociatedObject_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e) { var element = sender as FrameworkElement; element.Effect = (Effect)new DropShadowEffect() { Color = Colors.Transparent, ShadowDepth = 0 }; } /// <summary> /// 鼠标移入事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void AssociatedObject_MouseMove(object sender, System.Windows.Input.MouseEventArgs e) { var element = sender as FrameworkElement; //鼠标移入时候的颜色设置 element.Effect = (Effect)new DropShadowEffect() { Color = Colors.Red, ShadowDepth = 0 }; } /// <summary> /// 解除关联的事件 /// </summary> protected override void OnDetaching() { base.OnDetaching(); AssociatedObject.MouseMove -= AssociatedObject_MouseMove; AssociatedObject.MouseLeave -= AssociatedObject_MouseLeave; } } }
xaml:
<UserControl x:Class="MyWpf.MyBehavior" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:MyWpf.CommonService" xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" mc:Ignorable="d" d:DesignHeight="450" d:DesignWidth="800"> <Grid> <StackPanel> <TextBox Width="100" Height="30" Margin="40"> <i:Interaction.Behaviors> <local:EffectBehavior/> </i:Interaction.Behaviors> </TextBox> <Button Width="100" Height="30" Margin="40"> <i:Interaction.Behaviors> <local:EffectBehavior/> </i:Interaction.Behaviors> </Button> </StackPanel> </Grid> </UserControl>
结果: