这一节,我们来利用Behavior行为实现控件的缩放效果。要实现此效果,需要在鼠标的滚轮事件下,通过获取Delta值去设置ScaleTransform缩放对象的ScaleX和ScaleY,从而将控件进行放大或缩小。
下面是缩放行为的定义代码:
public class ScaleBehavior : Behavior<FrameworkElement>
{
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.MouseWheel += AssociatedObject_MouseWheel;
}
private void AssociatedObject_MouseWheel(object sender,
System.Windows.Input.MouseWheelEventArgs e)
{
//首次滚动时,判断RenderTransform的类型是否为ScaleTransform
if (!(AssociatedObject.RenderTransform is ScaleTransform))
{
AssociatedObject.RenderTransform = new ScaleTransform()
{
CenterX = AssociatedObject.ActualWidth / 2,
CenterY = AssociatedObject.ActualHeight / 2,
};
}
var transform = AssociatedObject.RenderTransform as ScaleTransform;
double scale = e.Delta * 0.001;
transform.ScaleX += scale;
transform.ScaleY += scale;
}
protected override void OnDetaching()
{
base.OnDetaching();
AssociatedObject.MouseWheel -= AssociatedObject_MouseWheel;
}
}
然后,我们在上一节的代码中稍作修改,引用这个行为。
<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/>
<behavior:ScaleBehavior/>
</i:Interaction.Behaviors>
</Border>
<TextBlock Text="WPF中文网"
Foreground="White"
FontSize="60"
Canvas.Left="92"
Canvas.Top="75">
<i:Interaction.Behaviors>
<behavior:ShadowBehavior/>
<behavior:ScaleBehavior/>
</i:Interaction.Behaviors>
</TextBlock>
<TextBlock Text="Behavior行为之缩放效果"
Foreground="White"
FontSize="40"
Canvas.Left="21"
Canvas.Top="182">
<i:Interaction.Behaviors>
<behavior:ShadowBehavior/>
<behavior:ScaleBehavior/>
</i:Interaction.Behaviors>
</TextBlock>
</Canvas>
</Window>
缩放之前的效果
缩放之后的效果
当前课程源码下载:(注明:本站所有源代码请按标题搜索)
文件名:109-《行为之控件缩放效果》-源代码
链接:https://pan.baidu.com/s/1yu-q4tUtl0poLVgmcMfgBA
提取码:wpff
——重庆教主 2023年11月21日