WPF移动Window窗体(鼠标点击左键移动窗体自定义行为)

原文:WPF移动Window窗体(鼠标点击左键移动窗体自定义行为)

XAML代码部分:1、引用System.Windows.Interactivity

        2、为指定的控件添加一个拖动的行为

        3、很简单的了解行为的作用和用法

<Window
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
        xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions" 
        xmlns:behavior="clr-namespace:SDT.Client.Behaviors"
        x:Class="SDT.Client.MainWindow"
        Title="MainWindow" Height="350" Width="525" WindowStyle="None">
    <Rectangle Fill="#FFEE602B" HorizontalAlignment="Left" Height="39" Margin="10,10,0,0" Stroke="Black" VerticalAlignment="Top" Width="497">
        <i:Interaction.Behaviors>
            <behavior:MouseDragWindowBehavior />
        </i:Interaction.Behaviors>
    </Rectangle>
</Window>

 

自定义行为代码:

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Interactivity;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace SDT.Client.Behaviors
{
    /// <summary>
    /// 鼠标点击左键移动窗体自定义行为
    /// </summary>
    public class MouseDragWindowBehavior : Behavior<FrameworkElement>
    {
        public MouseDragWindowBehavior()
        {
            /* 在创建WPF自定义窗体时,往往会取消默认的窗体样式,
             * 那么当WindowStyle设置为None时,
             * 需要移动窗体时就必需对某一个UIElement控件进去指定的DragMove操作;
             * 
             * 下面就为指定的控件绑定一个点击左键事件移动窗体的行为
             */
        }
        private Window m_CurrentWindow;

        protected override void OnAttached()
        {
            base.OnAttached();
            //为行为对象添加一个模拟移动的点击事件
            this.AssociatedObject.PreviewMouseLeftButtonDown += OnDragMove;
        }

        private void OnDragMove(object sender, MouseButtonEventArgs e)
        {
            //获取鼠标坐标
            Point position = e.GetPosition(AssociatedObject);
            //鼠标坐标在控件范围内运行移动窗体
            if (position.X < AssociatedObject.ActualWidth && position.Y < AssociatedObject.ActualHeight)
            {
                //获取当前附加行为的控件所在窗体(Window对象)
                if (m_CurrentWindow == null)
                {
                    m_CurrentWindow = Window.GetWindow(AssociatedObject);
                }
                m_CurrentWindow.DragMove();
            }
        }
    }
}

 

WPF移动Window窗体(鼠标点击左键移动窗体自定义行为)

上一篇:错误: Cause: java.lang.IllegalArgumentException: Mapped Statements collection does not contain value for studentDao.insert


下一篇:php使用try catch 捕捉异常