WPF中DataGrid设置默认选中行

1、DataGrid命名为planDataGrid

<DataGrid ItemsSource="{Binding PlanList}" SelectedItem="{Binding SelectedItem}" x:Name="planDataGrid" AutoGenerateColumns="False" CanUserAddRows="False"

GridLinesVisibility="All" FontSize="12" ColumnHeaderHeight="42" RowHeaderWidth="0" EnableRowVirtualization="False" VirtualizingPanel.IsVirtualizing="False">

</DataGrid>

2、 SetSelectedItemFirstRow(page.planDataGrid);调用方法,获取到前端界面的DataGrid,传给后端使用。

cs 复制代码
 void SetSelectedItemFirstRow(object dataGrid)
 {
     //若目标datagrid为空,抛出异常
     if (dataGrid == null)
     {
         throw new ArgumentNullException("目标无" + dataGrid + "无法转换为DataGrid");
     }
     //获取目标DataGrid,为空则抛出异常
     System.Windows.Controls.DataGrid dg = dataGrid as System.Windows.Controls.DataGrid;
     if (dg == null)
     {
         throw new ArgumentNullException("目标无" + dataGrid + "无法转换为DataGrid");
     }
     //数据源为空则返回
     if (dg.Items == null || dg.Items.Count < 1)
     {
         return;
     }

     dg.SelectedItem = dg.Items[0];
     dg.CurrentColumn = dg.Columns[0];
     dg.ScrollIntoView(dg.SelectedItem, dg.CurrentColumn);
     //获取焦点,滚动为目标行
     dg.Focus();
     dg.SelectedItem = selectedItem;//设置选中行
     dg.CurrentColumn = dg.Columns[0];
     dg.ScrollIntoView(dg.SelectedItem, dg.CurrentColumn);
     var item = dg.SelectedItem as PlanDataModel;
     ObservableCollection<CoilListModel> clm = new ObservableCollection<CoilListModel>();
     DBHandle.GetCoilsByJobId(item, ref clm);

     CoilList = clm;
     page.coilDataGrid.ItemsSource = CoilList;
 }
相关推荐
mengge.cloud13 小时前
存储技术基础小白教程
linux·运维·服务器·wpf·存储
DreamLife☼20 小时前
复杂Agent系统架构设计
系统架构·wpf·agent·组件·设计·构架·说明
SamChan901 天前
PDF翻译服务端到端基准测试:4款主流方案的吞吐量、延迟、内存占用对比
服务器·网络·python·ai·pdf·wpf
bugcome_com1 天前
Avalonia 控件模板实战:从 WPF 迁移自定义 Button 样式的完整指南
wpf
七夜zippoe1 天前
DolphinDB 故障排查实战:系统、数据库与集群常见问题诊断
数据库·wpf·集群·常见问题·故障排查·dolphindb
dalong102 天前
WPF:箭头绘制程序
wpf·自定义绘制
张工在路上3 天前
WPF 布局基础概述
大数据·hadoop·wpf
迪飞特科技4 天前
分布式事务下 Spring 声明式事务失效的 3 种修复方案
分布式·spring·wpf
2601_962174177 天前
Redis 简介
数据库·redis·wpf
SamChan908 天前
Python+PyMuPDF提取PDF表格并翻译:表格结构检测与双语重建实战
windows·python·ai·pdf·wpf