C# WPF 记录DataGrid的表头顺序,下次打开界面时应用到表格中

效果:

代码实现

前端

XML 复制代码
 <DataGrid x:Name="DataGrid1"

<!--定义当列位置变化后的触发事件-->
  CanUserReorderColumns="True"
  ColumnReordered="DataGrid_ColumnReordered"

  rubyer:ControlHelper.FocusedForegroundBrush="{StaticResource Accent}"
  AutoGenerateColumns="False"
  BorderThickness="1"
  CanUserAddRows="False"
  GridLinesVisibility="All"

<!-- 定义当列位置变化时触发的事件-->
  ColumnDisplayIndexChanged="DataGrid_ColumnDisplayIndexChanged"

  HeadersVisibility="ALL"
  IsReadOnly="{Binding DataGridIsReadOnly, UpdateSourceTrigger=PropertyChanged}"
               Height="620"
  ItemsSource="{Binding Ibo}"
  SelectionMode="Single"
  FrozenColumnCount="1"
  PreviewMouseDown="DataGrid_PreviewMouseDown"
  PreviewMouseUp="DataGrid_PreviewMouseUp">
     <DataGrid.Columns>
     ......列的定义
     </DataGrid.Columns>
</DataGrid>

后端

cs 复制代码
 public partial class TraceTable : UserControl
 {

     private Dictionary<string, int> Column2Index;
     private t_user_column_indexDAL t_User_Column_IndexDAL = new t_user_column_indexDAL();
     private bool IsApplying;
     public TraceTable()
     {
         InitializeComponent();
         this.DataContext = App.Current.Services.GetService<TraceTableViewModel>();
         ApplySavedColumnOrder();

     }

     private void ApplySavedColumnOrder()
 {
     //在把数据库的表头顺序应用到DataGrid中时也会触发DataGrid_ColumnDisplayIndexChanged事件
     //所以要用IsApplying 记录是否正在初始化
     IsApplying = true;
     //从t_user_column_index中拿到dictionary并序列化

     string sql = $"select dictionary as toolStr1 from t_user_column_index where userid = '{UserSession.UserId}'";
     string dictionaryJson = t_User_Column_IndexDAL.db.SqlQueryable<ToolStr30>(sql).ToList().Count > 0 ?
         t_User_Column_IndexDAL.db.SqlQueryable<ToolStr30>(sql).ToList()[0].toolStr1:
         null;

     if (string.IsNullOrEmpty(dictionaryJson))
     {
         Column2Index = new Dictionary<string, int>
     {
         {"采购回复交期",1},
         {"供应商名称",2},
         {"品名",3},
         {"规格描述",4},
         {"采购订单号",5},
         {"采购数量(计量)",6},
         {"未交数量(计量)",7},
         {"单位",8},
         {"生产订单号",9},
         {"异常反馈",10},
         {"采购说明",11},
         {"请购日期",12},
         {"标准周期",13},
         {"采购标准周期",14},
         {"料号",15},
         {"采购建立日期",16},
         {"采购周期",17},
         {"来源单号",18},
         {"行号",19},
         {"现存量",20},
         {"收货数量(计量)",21},
         {"已退货数(计量)",22},
         {"实际入库数(计量)",23},
         {"含税单价",24},
         {"含税金额",25},
         {"入库单号",26},
         {"采购员",27},
         {"请购人",28},
         {"采购制单人",29},
         {"请购制单人",30},
         {"请购单备注",31},
         {"采购订单结案状态",32},
         {"已暂收数量(计量)",33},
         {"最后交货日期",34},
         {"逾期天数(负数未到期)",35},
         {"品质异常报告日期",36},
         {"品质问题描述",37},
         {"处理结论",38},
         {"交货结案日期",39},
         {"PMC交单日期",40},
         {"采购理论交期",41},
         {"要求交期",42},
         {"订单回传日期",43},
         {"色板_模板_图纸提供情况",44},
         {"预付款比例",45},
         {"预付款支付日期",46},
         {"尾款比例",47},
         {"尾款支付日期",48},
         {"备注",49},
         {"可用量",50},
         {"采购到货日期",51},
         {"财务交单日期",52},
         {"修改日期_请购",53},
         {"修改日期_采购",54},
         {"PMC要求交货日期",55}
     };
     }
     else
     {
         // 将 JSON 字符串解析为 JObject
         JObject jObject = JObject.Parse(dictionaryJson);

         // 将 JObject 转换为 Dictionary<string, int>
         Column2Index = jObject.ToObject<Dictionary<string, int>>();
     }

     for (int i = 0; i < DataGrid1.Columns.Count; i++)
     {
         var column = DataGrid1.Columns[i];

         if (column.Header.Equals("操作"))
         {
             // 如果列头为"操作",跳过该列
             continue;
         }
         Column2Index.TryGetValue(column.Header.ToString(), out int value);
         column.DisplayIndex = value; // 设置列的显示顺序
     }
     IsApplying = false;

 }

    private void DataGrid_ColumnDisplayIndexChanged(object sender, DataGridColumnEventArgs e)
    {
        if (IsApplying)
        {
            return;
        }
        var column = e.Column;
        // 获取变更后的列和新的列显示顺序
        int newIndex = column.DisplayIndex;
        Column2Index[column.Header.ToString()] = newIndex;
    }


    private void DataGrid_ColumnReordered(object sender, DataGridColumnEventArgs e)
    {
        string json = JsonConvert.SerializeObject(Column2Index);

        //先查询有无已经保存的数据
        string sql = $"select * from t_user_column_index where userid = '{UserSession.UserId}'";
        List<ToolStr30> sqlResult = t_User_Column_IndexDAL.db.SqlQueryable<ToolStr30>(sql).ToList();
        if (sqlResult.Count>0)
        {
            sql = $"update t_user_column_index  set dictionary = '{json}' where userid = '{UserSession.UserId}'";
            t_User_Column_IndexDAL.db.SqlQueryable<ToolStr30>(sql).ToList();

        }
        else
        {
            //将改变后的dictionary保存到数据库中
            sql = $"insert into t_user_column_index (userid,dictionary) values('{UserSession.UserId}','{json}')";
            var lists = t_User_Column_IndexDAL.db.SqlQueryable<ToolStr30>(sql).ToList();
        }
        

    }

}

数据库

思路:

1,登录进来时查询数据库有无自定义的列表头属性;

-- 有则拿出来序列化成Dictionary<string,int> Column2Index;

-- 没有则手动将表头和索引的对应关系保存到Dictionary<string,int> Column2Index中;

2,当表头位置发生变化触发DataGrid_ColumnDisplayIndexChanged 事件,在该事件中修改Column2Index中对应的表头的索引位置;

3,当DataGrid_ColumnDisplayIndexChanged 结束后还会触发DataGrid_ColumnReordered 事件,该事件实在表头位置变化结束后触发,在这里面将修改后的Column2Index保存到数据库中

相关推荐
小码编匠10 小时前
WPF 中的高级交互通过右键拖动实现图像灵活缩放
后端·c#·.net
唐青枫17 小时前
C#.NET 定时任务与队列利器:Hangfire 完整教程
c#·.net
hez20101 天前
Runtime Async - 步入高性能异步时代
c#·.net·.net core·clr
mudtools2 天前
.NET驾驭Word之力:玩转文本与格式
c#·.net
唐青枫2 天前
C#.NET 数据库开发提速秘籍:SqlSugar 实战详解
c#·.net
mudtools2 天前
.NET驾驭Word之力:理解Word对象模型核心 (Application, Document, Range)
c#·.net
侃侃_天下3 天前
最终的信号类
开发语言·c++·算法
echoarts3 天前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
Aomnitrix3 天前
知识管理新范式——cpolar+Wiki.js打造企业级分布式知识库
开发语言·javascript·分布式
大飞pkz3 天前
【设计模式】C#反射实现抽象工厂模式
设计模式·c#·抽象工厂模式·c#反射·c#反射实现抽象工厂模式