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

时间:2022-06-22 14:51:20

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="" Width="" WindowStyle="None">
<Rectangle Fill="#FFEE602B" HorizontalAlignment="Left" Height="" Margin="10,10,0,0" Stroke="Black" VerticalAlignment="Top" Width="">
<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();
}
}
}
}