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

WPF 为DataGrid添加行双击行为

双击DataGrid中的行,然后做一些事情,要点:

1、为DataGrid添加事件监听,而不是为每个DataGridRow添加事件监听;
2、双击的位置一般为单元格或单元格内的元素,所以这里牵涉到碰撞检测和父元素查找;
3、单元格内若有功能元素,如:删除按钮,复选按钮等。要规避点击冲突。

实现过程

1. 安装行为包

安装 Microsoft.Xaml.Behaviors.Wpf NuGet包

2. 父元素查找工具类

下面与是市面上见到的大多父元素查找不大一样,VisualTreeHelper.GetParent 遇到非 Visual 或 Visual3D 类型会抛出异常,此方法做了特殊处理。

public static class VisualHelper
{/// <summary>/// 查找父元素/// </summary>/// <typeparam name="T"></typeparam>/// <param name="element"></param>/// <param name="filter"></param>/// <returns></returns>public static T FindParent<T>(this DependencyObject element, Func<T, bool> filter = null) where T : DependencyObject{while (element != null){if (element is T && (filter == null || filter.Invoke(element as T))){return element as T;}// 安全的父元素获取DependencyObject parent = null;try{if (element is Visual || element is Visual3D){parent = VisualTreeHelper.GetParent(element);}else{parent = LogicalTreeHelper.GetParent(element);}}catch{parent = LogicalTreeHelper.GetParent(element);}element = parent;}return null;}
}

3. 自定义一个双击行行为

/// <summary>
/// 为DataGrid添加双击行行为
/// </summary>
public class DataGridRowDoubleClickBehavior : Behavior<DataGrid>
{public static readonly DependencyProperty CommandProperty =DependencyProperty.Register("Command", typeof(ICommand), typeof(DataGridRowDoubleClickBehavior));public ICommand Command{get { return (ICommand)GetValue(CommandProperty); }set { SetValue(CommandProperty, value); }}protected override void OnAttached(){base.OnAttached();AssociatedObject.PreviewMouseDoubleClick += OnPreviewMouseDoubleClick;}protected override void OnDetaching(){base.OnDetaching();AssociatedObject.PreviewMouseDoubleClick -= OnPreviewMouseDoubleClick;}private void OnPreviewMouseDoubleClick(object sender, MouseButtonEventArgs e){/*// 直接检查点击的是否是DataGridRowvar source = e.OriginalSource as DependencyObject;var row = source.FindParent<DataGridRow>();if (row == null){return;}*/var dataGrid = sender as DataGrid;if (dataGrid == null){return;}// 使用HitTest获取点击位置的实际元素var hitTestResult = VisualTreeHelper.HitTest(dataGrid, e.GetPosition(dataGrid));if (hitTestResult == null){return;}// 检查是否点击了按钮var button = hitTestResult.VisualHit.FindParent<Button>();if (button != null){// 如果是按钮,不处理行双击return;}var row = hitTestResult.VisualHit.FindParent<DataGridRow>();if (row == null){return;}// 处理行双击if (Command?.CanExecute(row.Item) == true){Command.Execute(row.Item);e.Handled = true;}}
}

4. 在XAML中使用

<DataGrid><i:Interaction.Behaviors><!--controls:ControlCommands.DoubleClick我这里是用的静态成员 你需要换成你的ViewModel中的命令--><core:DataGridRowDoubleClickBehavior Command="{x:Static controls:ControlCommands.DoubleClick}" /></i:Interaction.Behaviors>
</DataGrid>

大功告成。非MVVM模式,逻辑类似。不再介绍。

http://www.jsqmd.com/news/534068/

相关文章:

  • LoRaWAN大规模部署如何避免空中资源挤兑
  • C/C++ snprintf 函数详解
  • 四川省不燃型复合膨胀聚苯乙烯保温板优质厂家推荐 - 深度智识库
  • 金三银四已失效,Java程序员请早点认清现实!
  • 美团偷偷删你相册照片,客服甩锅“插件冲突”?
  • 芯片功耗优化实战:Clock Gating技术详解与实现避坑指南
  • 基于CCMusic的音乐推荐系统开发:MySQL数据库集成实践
  • 剖析2026年平衡机专业供应商,上海申克机械性能超好用 - myqiye
  • 耙式真空干燥机厂家哪家好?口碑品牌+源头生产厂家推荐 - 品牌推荐大师1
  • PyTorch 2.8项目版本管理实战:GitHub与Git标准工作流
  • s2-pro实战教程:用curl命令直连API实现自动化语音生成流水线
  • 轻量级AI模型实测:Ollama部署Phi-3-mini-4k-instruct效果如何?
  • 全国有好用的平衡机厂推荐吗,上海申克机械表现如何 - 工业推荐榜
  • Granite TimeSeries FlowState R1多步预测效果展示:滚动预测与置信区间可视化
  • AI 辅助开发实战:基于 Spark 的毕业设计项目高效构建指南
  • yfinance高效工具实战指南:从数据获取到智能分析
  • ChatGPT Cookie 使用指南:从基础配置到安全实践
  • RMBG-2.0多场景应用:电商主图/证件照/直播贴纸/设计素材一键去背
  • Spec Kit:规范驱动开发的终极解决方案,如何让AI助手成为你的高效编码伙伴?
  • 智能多态员中的接口统一与实现多样
  • 终极指南:如何用F_Record插件轻松录制Photoshop绘画全过程
  • 天虹提货券回收1分钟高效流程解析与价格表 - 淘淘收小程序
  • 使用Docker快速部署VLLM推理服务:从镜像拉取到OpenAI兼容API测试
  • C++ STL 容器内存优化策略
  • ha_xiaomi_home:打造智能家居中枢的零代码集成方案
  • 说说南京九菱亚克力精密加工,它在苏州无锡南通上海靠谱吗? - 工业品牌热点
  • 永辉超市卡回收避坑指南,擦亮双眼,守护资金安全 - 京顺回收
  • 开源音乐体验革命:foobox-cn如何重塑你的听觉世界
  • 电化学数据处理那些事儿
  • 终极OpenCart电商平台完整指南:新手快速上手指南