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;
 }
相关推荐
爱吃烤鸡翅的酸菜鱼2 天前
Java 事件发布-订阅机制全解析:从原生实现到主流中间件
java·中间件·wpf·事件·发布订阅
武藤一雄3 天前
WPF中ViewModel之间的5种通讯方式
开发语言·前端·microsoft·c#·wpf
CSharp精选营3 天前
都是微软亲儿子,WPF凭啥干不掉WinForm?这3个场景说明白了
c#·wpf·跨平台·winform
baivfhpwxf20233 天前
wpf TextBlock 控件如何根据内容换行?
wpf
亘元有量-流量变现3 天前
鸿蒙、安卓、苹果音频设备技术深度解析与开发实践
android·wpf·harmonyos·亘元有量·积分墙
软泡芙3 天前
【Bug】ReactiveUI WPF绑定中依赖属性不更新的问题分析与解决方案
java·bug·wpf
浪扼飞舟3 天前
WPF输入验证(ValidationRule)
java·javascript·wpf
IOFsmLtzR5 天前
Flink Agents 源码解读 --- (5) --- ActionExecutionOperator
microsoft·flink·wpf
廋到被风吹走6 天前
【AI】Codex 复杂任务拆解:从“一气呵成“到“步步为营“
人工智能·wpf
希望永不加班6 天前
SpringBoot 整合 Redis 缓存
spring boot·redis·后端·缓存·wpf