Winform控件绑定数据

本文介绍了C# Winform中控件如何绑定数据,包括简单控件、列表控件和表格控件的绑定方式,讲解了BindingList、DataTable、BindingSource的使用,并提供了UI线程全局类以支持多线程数据源更新。
摘要由CSDN通过智能技术生成

简介#

在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;
       
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

jh035

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值