简介#
在C#中提起控件绑定数据,大部分人首先想到的是WPF,其实Winform也支持控件和数据的绑定。
Winform中的数据绑定按控件类型可以分为以下几种:
- 简单控件绑定
- 列表控件绑定
- 表格控件绑定
绑定基类#
绑定数据类必须实现INotifyPropertyChanged接口,否则数据类属性的变更无法实时刷新到界面,但可以从界面刷新到类。
为了方便,我们设计一个绑定基类:
/// <summary>
/// 数据绑定基类
/// </summary>
public abstract class BindableBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected bool SetProperty<T>(ref T field, T newValue, [CallerMemberName] string propertyName = null)
{
if (!EqualityComparer<T>.Default.Equals(field, newValue))
{
field = newValue;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
return true;
}
return false;
}
}
需要绑定的数据类继承绑定基类即可:
/// <summary>
/// 数据类
/// </summary>
public class Data : BindableBase
{
private int id = 0;
private string name = string.Empty;
public int ID { get => id; set => SetProperty(ref id, value); }
public string Name { get => name; set => SetProperty(ref name, value); }
}
功能扩展#
主要为绑定基类扩展了以下两个功能:
- 获取属性的Description特性内容
- 从指定类加载属性值,对象直接赋值是赋值的引用,控件绑定的数据源还是之前的对象
这两个功能不属于绑定基类的必要功能,但可以为绑定提供方便,所以单独放在扩展方法类里面。
代码如下:
/// <summary>
/// 数据绑定基类的扩展方法
/// </summary>
public static class BindableBaseExtension
{
/// <summary>
/// 获取属性的描述,返回元组格式为 Item1:描述信息 Item2:属性名称
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public static Tuple<string, string>[] GetDescription(this BindableBase bindData)
{
var proAry = bindData.GetType().GetProperties();
var desAry = new Tuple<string, string>[proAry.Length];
string desStr;
for (int i = 0; i < proAry.Length; i++)
{
var attrs = (DescriptionAttribute[])proAry[i].GetCustomAttributes(typeof(DescriptionAttribute), false);
desStr = proAry[i].Name;
foreach (DescriptionAttribute attr in attrs)
{
desStr = attr.Description;