WPF——对控件进行缩放

对控件进行缩放

控件的缩放属于 Transform, 而对于需要以鼠标位置为中心进行缩放则为 MatrixTransform, 为保证 MVVM 的一致性,采用 System.Windows.Interactivity 中的 Behavior 实现, 下面为实现控件缩放的方法.

StackOverflow: WPF Zoom Canvas Center on Mouse Position

ZoomOnMouseWheel.cs

using System.Windows;
using System.Windows.Input;
using System.Windows.Interactivity;
using System.Windows.Media;

namespace Demo.Utils
{
    public class ZoomOnMouseWheel : Behavior<FrameworkElement>
    {
        public Key? ModifierKey { get; set; } = null;
        public TransformMode TranformMode { get; set; } = TransformMode.Render;

        private Transform _transform;

        protected override void OnAttached()
        {
            if (TranformMode == TransformMode.Render)
            {
                _transform = Associatedobject.RenderTransform = new MatrixTransform();
            }
            else
            {
                _transform = Associatedobject.LayoutTransform = new MatrixTransform();
            }

            Associatedobject.MouseWheel += Associatedobject_MouseWheel;
        }

        protected override void OnDetaching()
        {
            Associatedobject.MouseWheel -= Associatedobject_MouseWheel;
        }

        private void Associatedobject_MouseWheel(object sender, MouseWheelEventArgs e)
        {
            if ((!ModifierKey.HasValue || !Keyboard.IsKeyDown(ModifierKey.Value)) && ModifierKey.HasValue)
            {
                return;
            }

            if (!(_transform is MatrixTransform transform))
            {
                return;
            }

            var pos1 = e.GetPosition(Associatedobject);
            var scale = e.Delta > 0 ? 1.1 : 1 / 1.1;
            var mat = transform.Matrix;
            mat.ScaleAt(scale, scale, pos1.X, pos1.Y);
            transform.Matrix = mat;
            e.Handled = true;
        }
    }

    public enum TransformMode
    {
        Layout,
        Render,
    }
}

View.xaml

<UserControl ...
    xmlns:interactivity="http://schemas.microsoft.com/expression/2010/interactivity"
    xmlns:local="clr-namespace:Demo.Utils">

    <Canvas>
        <interactivity:Interaction.Behaviors>
            <local:ZoomOnMouseWheel ModifierKey="LeftCtrl" TransformMode="Layout">
        </interactivity:Interaction.Behaviors>
    </Canvas>
</UserControl>

相关文章

Windows2012R2备用域控搭建 前置操作 域控主域控的主dns:自...
主域控角色迁移和夺取(转载) 转载自:http://yupeizhi.blo...
Windows2012R2 NTP时间同步 Windows2012R2里没有了internet时...
Windows注册表操作基础代码 Windows下对注册表进行操作使用的...
黑客常用WinAPI函数整理之前的博客写了很多关于Windows编程的...
一个简单的Windows Socket可复用框架说起网络编程,无非是建...