BDU/BDU/Windows/SystemConfigWindow.xaml.cs
2026-03-16 14:24:10 +08:00

87 lines
2.6 KiB
C#

using BDU;
using MahApps.Metro.Controls;
using Newtonsoft.Json;
using System;
using System.IO;
using System.Reflection;
using System.Windows;
using System.Windows.Input;
namespace BDU.Windows
{
public partial class SystemConfigWindow : MetroWindow
{
// 配置副本(用于界面绑定)
public SystemConfig ConfigCopy { get; } = new();
public SystemConfigWindow()
{
InitializeComponent();
// 使用反射复制配置属性
CopyConfigProperties(SystemConfig.Instance, ConfigCopy);
DataContext = this;
}
// 反射复制属性方法(排除 JsonIgnore 属性)
private void CopyConfigProperties(SystemConfig source, SystemConfig target)
{
Type type = typeof(SystemConfig);
PropertyInfo[] properties = type.GetProperties();
foreach (PropertyInfo property in properties)
{
// 跳过 JsonIgnore 属性和只读属性
if (Attribute.IsDefined(property, typeof(JsonIgnoreAttribute)) || !property.CanWrite)
{
continue;
}
object value = property.GetValue(source)!;
property.SetValue(target, value);
}
}
// 保存配置到文件
private void SaveConfigToFile()
{
try
{
// 使用实例的SystemPath确保路径正确
string configPath = Path.Combine(ConfigCopy.SystemPath, "system.config");
// 确保目录存在
Directory.CreateDirectory(ConfigCopy.SystemPath);
// 序列化保存
string json = JsonConvert.SerializeObject(ConfigCopy, Formatting.Indented);
File.WriteAllText(configPath, json);
}
catch (Exception ex)
{
MessageBox.Show($"保存配置失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
private void GroupBox_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (e.ChangedButton == MouseButton.Left)
{
DragMove();
}
}
private void Save_Click(object sender, RoutedEventArgs e)
{
CopyConfigProperties(ConfigCopy, SystemConfig.Instance);
SaveConfigToFile();
SystemConfig.Instance.LoadFromFile();
Close();
}
private void Cancel_Click(object sender, RoutedEventArgs e)
{
Close();
}
}
}