当前位置: 首页 > 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.fuzeviewer.com/news/522/

相关文章:

  • 噪声点验证码的图像处理与识别思路
  • 1027
  • 关系运算符逻辑运算符
  • 《程序员修炼之道》 阅读笔记三
  • 第四篇:docker底层原理
  • 关于springboot+Servlet报错404的问题
  • Codechef Painting Tree 题解 [ 蓝 ] [ 树形 DP ] [ 概率期望 ] [ 分类讨论 ]
  • 【CI130x 离在线】如何运行 curl 脚本
  • 这才是真正的AI NAS!极空间私有云Z2Ultra评测
  • 新东方第三节课名言作文
  • 十月阅读_3
  • 中考_体育
  • 常见问题处理 --- phpstudy启动mysql失败
  • 20232308 2025-2026-1 《网络与系统攻防技术》实验三实验报告
  • 【密码学实战】openHiTLS PKCS12命令行程序: PKCS12文件生成与解析
  • 「CTSC2017-游戏」题解
  • vue3 vue3-form-element表单生成工具 输入框增加后缀
  • 20232402 2025-2026-1 《网络与系统攻防技术》实验三实验报告
  • 掘金2025年:数字化商业浪潮下,如何选对平台与伙伴?一站式多商户商城系统推荐榜发布,多商户商城代理招募/多商户项目合伙人加盟/一站式开店代理项目加盟
  • 为医疗器械行业搭建“数字桥梁”,破解协同效率与合规难题
  • PostgreSQL 服务版
  • 20232307 2025-2026-1 《网络与系统攻防技术》实验三实验报告
  • 2025年10月办公家具公司评价榜:基于真实数据的权威推荐清单
  • vue+antv/x6项目使用问题
  • 《程序员修炼之道:从小工到专家》前五分之一观后感
  • 坐标系与投影关系
  • 用gdb的动态视角看ret2text的实现
  • 1027随笔
  • ask_skill
  • SVN 主分支合并之通过主分支合并子分支执行流程