当前位置: 首页 > news >正文

对Grid绑定移动

在WPF中,一般移动在Window中写

this.DragMove();

但是这样可能会污染View的纯净性质,如果不喜欢这样的写法,可以自己扩展代码
1、使用Command在ViewModel绑定
2、使用方法在Grid中自定义完成
总体思路都是一样的
现在给出我的邪门写法
首先扩展下命令行为

public static class CommandBehavior
{public static readonly DependencyProperty CommandProperty = DependencyProperty.RegisterAttached("Command", typeof(ICommand), typeof(CommandBehavior), new PropertyMetadata(null, CommandPropertyChanged));public static readonly DependencyProperty ParameterProperty = DependencyProperty.RegisterAttached("Parameter", typeof(object), typeof(CommandBehavior), new PropertyMetadata(null));public static void SetParameter(UIElement element, object value){element.SetValue(ParameterProperty, value);}public static object GetParameter(UIElement element){return element.GetValue(ParameterProperty);}public static void SetCommand(UIElement element, ICommand value){element.SetValue(CommandProperty, value);}public static ICommand GetCommand(UIElement element){return (ICommand)element.GetValue(CommandProperty);}private static void CommandPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e){if (d is UIElement uIElement){if (e.NewValue is ICommand){uIElement.MouseLeftButtonDown += Element_MouseLeftButtonDown;}else{uIElement.MouseLeftButtonDown -= Element_MouseLeftButtonDown;}}}private static void Element_MouseLeftButtonDown(object sender, MouseButtonEventArgs e){if (sender is UIElement element){ICommand command = GetCommand(element);if (command != null && command.CanExecute(null)){command.Execute(null);}}}
}

接着

 public class DragMoveHelper{public ICommand CreateDragMoveCommand(){return new TangdaoCommand(() =>Application.Current.Windows.OfType<Window>().SingleOrDefault(w => w.IsActive)?.DragMove());}}

这下我们可以使用ObjectDataProvider的MothedName

<ObjectDataProvider x:Key="drag"  MethodName="CreateDragMoveCommand" ObjectType="{x:Type local:DragMoveHelper}" />

对Grid进行静态绑定方法

<Grid Background="Transparent" behavior:CommandBehavior.Command="{Binding Source={StaticResource drag}}">

可以做到不需要污染View,不需要污染ViewModel,无伤静态写出控件移动

http://www.hskmm.com/?act=detail&tid=40198

相关文章:

  • 10.27博客
  • 关于结对编程的一些感悟
  • 结对编程心得
  • 关联子查询
  • AI概念
  • 工控modBus TCP, 服务端或客户端, 均可以与PHP 通讯
  • 衡量模型生成图片质量的指标
  • 代码大全2 第一章 与第二章
  • 第二十一天
  • 算法分析--分治--1.二分搜索
  • Experiment3
  • 20232403 2025-2026-1 《网络与系统攻防技术》实验三实验报告
  • CF995F Cowmpany Cowmpensation
  • 关系运算符逻辑运算符
  • LLM什么时候才能输出固定格式
  • 代码大全2
  • MCP和Function Calling的区别
  • 《程序员修炼之道》 阅读笔记三
  • 20251027
  • sg.绑定键盘事件
  • HT-083 CSP J/S题解
  • 壁纸收集
  • 洛谷 P6965 [NEERC 2016] Binary Code /「雅礼集训 2017 Day4」编码 【经验值记录】(2-SAT 学习笔记)
  • CentOS7安装Miniconda
  • 我在博客修文物
  • [题解]P7914 [CSP-S 2021] 括号序列
  • 102302116 田自豪 作业1
  • Windows11安装miniconda
  • PyPDF无限循环漏洞CVE-2025-62707技术分析
  • 关于springboot+Servlet报错404的问题