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;
 }
相关推荐
c#上位机9 小时前
wpf之Border
c#·wpf
SunflowerCoder9 小时前
WPF迁移avalonia之图像处理(一)
图像处理·wpf·avalonia
周杰伦fans10 小时前
WPF中的DataContext以及常见的绑定方式
wpf
没有bug.的程序员1 天前
Redis 数据结构全面解析:从底层编码到实战应用
java·数据结构·redis·wpf
somethingGoWay1 天前
wpf 自定义输入ip地址的文本框
wpf
秋月的私语2 天前
Wpf程序屏幕居中问题修复全记录
wpf
我要打打代码2 天前
WPF启动窗体的三种方式
wpf
R瑾安2 天前
mysql集群部署(Mysql Group Replication)
数据库·mysql·wpf
c#上位机2 天前
wpf中资源的使用
c#·wpf
Vae_Mars2 天前
WPF中的静态资源和动态资源
wpf