C#简单配置类及数据绑定

Rose ·
更新时间:2024-09-20
· 1100 次阅读

目录

1、简介

2、配置基类

3、派生配置类

4、数据绑定

4.1 Winform中的数据绑定

4.2 WPF下的数据绑定

1、简介

本文实现一个简单的配置类,原理比较简单,适用于一些小型项目。主要实现以下功能:

保存配置到json文件

从文件或实例加载配置类的属性值

数据绑定到界面控件

一般情况下,项目都会提供配置的设置界面,很少手动更改配置文件,所以选择以json文件保存配置数据。

2、配置基类

为了方便管理,项目中的配置一般是按用途划分到不同的配置类中,保存时也是保存到多个配置文件。所以,我们需要实现一个配置基类,然后再派生出不同用途的配置类。

配置基类需要引用 Json.NET ,继承数据绑定基类 BindableBase ,实现从其它实例加载数据的功能

基类代码如下:

using Newtonsoft.Json; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; namespace TestConfigDll { /// <summary> /// 配置基类,实现配置类的加载、保存功能 /// </summary> /// <typeparam name="T"></typeparam> public class ConfigBase<T> : BindableBase where T : class { /// <summary> /// 文件保存路径 /// </summary> private string filePath = ""; /// <summary> /// 设置文件保存路径 /// </summary> /// <param name="filePath"></param> public virtual void SetPath(string filePath) { this.filePath = filePath; } /// <summary> /// 保存到本地文件 /// </summary> public virtual void Save() { string dirStr = Path.GetDirectoryName(filePath); if (!Directory.Exists(dirStr)) { Directory.CreateDirectory(dirStr); } string jsonStr = JsonConvert.SerializeObject(this); File.WriteAllText(filePath, jsonStr); } /// <summary> /// 从本地文件加载 /// </summary> public virtual void Load() { if (File.Exists(filePath)) { var config = JsonConvert.DeserializeObject<T>(File.ReadAllText(filePath)); foreach (PropertyInfo pro in typeof(T).GetProperties()) { pro.SetValue(this, pro.GetValue(config)); } } } /// <summary> /// 从其它实例加载 /// </summary> /// <param name="config"></param> public virtual void Load(T config) { foreach (PropertyInfo pro in typeof(T).GetProperties()) { pro.SetValue(this, pro.GetValue(config)); } } /// <summary> /// 从其它实例加载,仅加载指定的属性 /// </summary> /// <param name="config"></param> /// <param name="proName"></param> public virtual void Load(T config, IEnumerable<string> proName = null) { foreach (PropertyInfo pro in typeof(T).GetProperties()) { if (proName == null || proName.Contains(pro.Name)) { pro.SetValue(this, pro.GetValue(config)); } } } } }

数据绑定基类 BindableBase 的实现参考WPF之数据绑定基类,

代码如下:

using System; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.CompilerServices; namespace TestConfigDll { public class BindableBase : INotifyPropertyChanged { /// <summary> /// 属性值更改时发生 /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// 检查属性是否已与设置值相等,设置属性并仅在必要时通知侦听器。 /// </summary> /// <typeparam name="T">属性的类型</typeparam> /// <param name="storage">对同时具有getter和setter的属性的引用</param> /// <param name="value">属性的所需值</param> /// <param name="propertyName">用于通知侦听器的属性的名称,此值是可选的,从支持CallerMemberName的编译器调用时可以自动提供。</param> /// <returns>如果值已更改,则为True;如果现有值与所需值匹配,则为false。</returns> protected virtual bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null) { if (EqualityComparer<T>.Default.Equals(storage, value)) return false; storage = value; RaisePropertyChanged(propertyName); return true; } /// <summary> /// 检查属性是否已与设置值相等,设置属性并仅在必要时通知侦听器。 /// </summary> /// <typeparam name="T">属性的类型</typeparam> /// <param name="storage">对同时具有getter和setter的属性的引用</param> /// <param name="value">属性的所需值</param> /// <param name="propertyName">用于通知侦听器的属性的名称,此值是可选的,从支持CallerMemberName的编译器调用时可以自动提供。</param> /// <param name="onChanged">属性值更改后调用的操作。</param> /// <returns>如果值已更改,则为True;如果现有值与所需值匹配,则为false。</returns> protected virtual bool SetProperty<T>(ref T storage, T value, Action onChanged, [CallerMemberName] string propertyName = null) { if (EqualityComparer<T>.Default.Equals(storage, value)) return false; storage = value; onChanged?.Invoke(); RaisePropertyChanged(propertyName); return true; } /// <summary> /// 引发此对象的PropertyChanged事件。 /// <param name="propertyName">用于通知侦听器的属性的名称,此值是可选的,从支持CallerMemberName的编译器调用时可以自动提供。</param> protected void RaisePropertyChanged([CallerMemberName] string propertyName = null) { OnPropertyChanged(new PropertyChangedEventArgs(propertyName)); } /// <summary> /// 引发此对象的PropertyChanged事件。 /// </summary> /// <param name="args">PropertyChangedEventArgs参数</param> protected virtual void OnPropertyChanged(PropertyChangedEventArgs args) { PropertyChanged?.Invoke(this, args); } } } 3、派生配置类

配置类的属性定义不能使用缩写形式,不用单例模式时可删除“配置单例”的代码,

配置类代码如下:

class TestConfig :ConfigBase<TestConfig> { #region 配置单例 /// <summary> /// 唯一实例 /// </summary> public static TestConfig Instance { get; private set; } = new TestConfig(); /// <summary> /// 静态构造函数 /// </summary> static TestConfig() { Instance.SetPath("Config\\" + nameof(TestConfig) + ".json"); Instance.Load(); } #endregion #region 属性定义 private string configStr = ""; public string ConfigStr { get { return this.configStr; } set { SetProperty(ref this.configStr, value); } } private int configInt =0; public int ConfigInt { get { return this.configInt; } set { if (value > 100) { SetProperty(ref this.configInt, value); } } } private bool configBool = false; public bool ConfigBool { get { return this.configBool; } set { SetProperty(ref this.configBool, value); } } #endregion } 4、数据绑定

一般数据绑定会定义一个Model类、ViewModel类,本文为了演示方便使用配置类同时承担两者的角色。

4.1 Winform中的数据绑定

先设计一个简单的界面,如下所示:

配置数据的加载、保存不用对每个控件进行操作,

后台代码如下:

public partial class Form1 : Form { private TestConfig testConfig = new TestConfig(); private List<string> proName = new List<string>(); public Form1() { InitializeComponent(); string textProName = nameof(textBox1.Text); textBox1.DataBindings.Add(textProName, testConfig, nameof(testConfig.ConfigStr)); textBox2.DataBindings.Add(textProName, testConfig, nameof(testConfig.ConfigInt)); string checkedProName= nameof(checkBox1.Checked); checkBox1.DataBindings.Add(checkedProName, testConfig, nameof(testConfig.ConfigBool)); proName.Add(textBox1.DataBindings[0].BindingMemberInfo.BindingField); proName.Add(textBox2.DataBindings[0].BindingMemberInfo.BindingField); proName.Add(checkBox1.DataBindings[0].BindingMemberInfo.BindingField); } private void button1_Click(object sender, EventArgs e) { testConfig.Load(TestConfig.Instance, proName); } private void button2_Click(object sender, EventArgs e) { TestConfig.Instance.Load(testConfig, proName); TestConfig.Instance.Save(); } }

如上所示, testConfig 作为中转,可以根据需求加载、保存配置类的部分或全部属性。如果对Winform下的数据绑感兴趣,可以参考 Winform 普通控件的双向绑定 。

4.2 WPF下的数据绑定

先设计一个简单的界面,如下所示:

<Window x:Class="WpfApp1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:WpfApp1" mc:Ignorable="d" Title="MainWindow" Height="208" Width="306.667"> <Grid> <Label Content="ConfigStr:" HorizontalAlignment="Left" Margin="18,16,0,0" VerticalAlignment="Top"/> <TextBox HorizontalAlignment="Left" Height="23" Margin="113,20,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="156" Text="{Binding Path=ConfigStr ,Mode=TwoWay}"/> <Label Content="ConfigInt:" HorizontalAlignment="Left" Margin="18,44,0,0" VerticalAlignment="Top"/> <TextBox HorizontalAlignment="Left" Height="23" Margin="113,48,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="156" Text="{Binding Path=ConfigInt ,Mode=TwoWay}"/> <Label Content="ConfigBool:" HorizontalAlignment="Left" Margin="18,74,0,0" VerticalAlignment="Top"/> <CheckBox Content="" HorizontalAlignment="Left" Margin="118,84,0,0" VerticalAlignment="Top" IsChecked="{Binding Path=ConfigBool ,Mode=TwoWay}"/> <Button Content="加载" HorizontalAlignment="Left" Margin="24,129,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/> <Button Content="保存" HorizontalAlignment="Left" Margin="194,129,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click_1"/> </Grid> </Window>

相对于WinformWPF控件绑定的操作由XAML实现,

后台代码如下:

/// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainWindow : Window { private TestConfig testConfig = new TestConfig(); public MainWindow() { InitializeComponent(); this.DataContext = testConfig; } private void Button_Click(object sender, RoutedEventArgs e) { testConfig.Load(TestConfig.Instance); } private void Button_Click_1(object sender, RoutedEventArgs e) { TestConfig.Instance.Load(testConfig); TestConfig.Instance.Save(); } }

上面的代码比较粗糙,没有记录已经绑定的属性,实际使用时可以进一步优化。

到此这篇关于C#简单配置类及数据绑定的文章就介绍到这了,更多相关C#简单配置类及数据绑定内容请搜索软件开发网以前的文章或继续浏览下面的相关文章希望大家以后多多支持软件开发网!

附件:

项目源码 提取码: pmwx



数据 数据绑定 C#

需要 登录 后方可回复, 如果你还没有账号请 注册新账号