C# WPF 记录DataGrid的表头顺序,下次打开界面时应用到表格中
效果:
代码实现
前端
<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>
后端
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保存到数据库中