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;
 }
相关推荐
凌镜icecraft3 天前
我改文件扩展名的时候那个警告弹窗再也不会弹出来了
windows·c#·wpf·explorer
光泽雨7 天前
控件Password附加属性
wpf
samble12 天前
从零搭建半导体设备上位机(十二):参数设置页,表单校验、范围校验与配方联动
wpf·数据校验·validationrule
samble20 天前
从零搭建半导体设备上位机(九):拖拽与交互,Adorner、DragDrop 与晶圆拖放信息
wpf·拖拽·adorner
郝学胜-神的一滴21 天前
AI 编程智能体 27:吃透MCP通信机制
人工智能·python·langchain·wpf·numpy·scikit-learn
波力海苔夹心脆67522 天前
C# WPF 资源字典详解:ResourceDictionary、MergedDictionaries 与自定义控件案例
开发语言·c#·wpf·入门教程·resource·资源字典
陈仓主教22 天前
# WPF CheckBox 控件详解与使用—WPF 中的控件(6)--复选框控件(CheckBox)
wpf
光泽雨24 天前
WPF 音视频四大核心方案对比
wpf·音视频
浪扼飞舟25 天前
WPF(数据绑定)
wpf
samble1 个月前
从零搭建半导体设备上位机(四):单实例、启动流程与配置文件,App 里那 526 行到底在干什么
wpf·配置文件·单实例