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

相关文章:

  • 10.27博客
  • [Mirror] LinuxMirrors: Linux 一键换源项目
  • 20232309 2025-2026-1 《网络与系统攻防技术》实验三实验报告
  • 衡量模型生成图片质量的指标
  • 【转载】‘tensorrt.tensorrt.Builder‘ object has no attribute ‘build_cuda_engine‘
  • 20232403 2025-2026-1 《网络与系统攻防技术》实验三实验报告
  • WPF datagrid mvvm loaded 100M items,prism.wpf,prism.dryioc
  • sg.绑定键盘事件
  • 壁纸收集
  • Windows11安装miniconda
  • 10.27 CSP-S模拟40 改题记录
  • 详细介绍:Redis多租户资源隔离方案:基于ACL的权限控制与管理
  • 20251027周一日记
  • 学校协同云盘怎么选?2025年10大热门教育网盘推荐与对比
  • GPU集群之间的交互
  • CF1267G Game Relics
  • 102302115方朴第一次作业
  • 解题报告-梦熊 CSP-S2025 模拟赛T2
  • 鄙“站”麻将和算24,刷新后会换
  • 20232422 2025-2026-1 《网络与系统攻防技术》实验三实验报告
  • 20232404 2025-2026-1 《网络与系统攻防技术》实验三实验报告
  • 「WC2014-紫荆花之恋」题解
  • 谢谢你周医生
  • 来源未知
  • Date 10.27
  • 10.27及动手动脑
  • go包装bing搜索
  • 鼾声识别芯片方案和睡眠产品的应用场景
  • 2025年工程管理软件公司综合推荐榜:助力建筑行业数字化升级
  • Excel高性能异步导出完整方案!