XAML 代码部分: 1, 引用 System.Windows.Interactivity
2, 为指定的控件添加一个拖动的行为
3, 很简单的了解行为的作用和用法
- <Windows
- 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>
- </Windows>
自定义行为代码:
- 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 Windows 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)
- {
- // 获取当前附加行为的控件所在窗体 (Windows 对象)
- if (m_CurrentWindow == null)
- {
- m_CurrentWindow = Windows.GetWindow(AssociatedObject);
- }
- m_CurrentWindow.DragMove();
- }
- }
- }
- }
来源: http://www.bubuko.com/infodetail-3034507.html