【WinForm.NET开发】设计具有更改通知的出色数据源

这篇具有很好参考价值的文章主要介绍了【WinForm.NET开发】设计具有更改通知的出色数据源。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

本文内容

  1. 简单绑定的更改通知
  2. 基于列表的绑定的更改通知
  3. 自定义控件的更改通知
  4. 应用 PropertyNameChanged 模式
  5. 实现 INotifyPropertyChanged 接口
  6. 同步绑定

Windows 窗体数据绑定最重要的概念之一是更改通知。 为确保数据源和绑定控件始终具有最新数据,必须为数据绑定添加更改通知。 具体来说,你希望确保绑定控件在对其数据源进行更改时得到通知。 数据源在对控件的绑定属性进行更改时得到通知。

根据数据绑定的类型,有不同类型的更改通知:

  • 简单绑定,其中单个控件属性绑定到对象的单个实例。

  • 基于列表的绑定,它可以包括绑定到列表中项属性的单个控件属性或绑定到对象列表的控件属性。

此外,如果正在创建要用于数据绑定的 Windows 窗体控件,必须将 PropertyNameChanged 模式应用于控件。 将模式应用于控件后,会将对控件的绑定属性的更改传播到数据源。

1、简单绑定的更改通知

对于简单绑定,业务对象必须在绑定属性的值更改时提供更改通知。 可以通过为业务对象的每个属性公开一个 PropertyNameChanged 事件来提供更改通知。 同时需要使用 BindingSource 或首选方法将业务对象绑定到控件,在该方法中业务对象实现 INotifyPropertyChanged 接口并在属性值更改时引发 PropertyChanged 事件。 使用实现 INotifyPropertyChanged 接口的对象时,不必使用 BindingSource 将对象绑定到控件。 但建议使用 BindingSource

2、基于列表的绑定的更改通知

Windows 窗体依靠绑定列表来向绑定控件提供提供属性更改和列表更改信息。 属性更改是更改列表项属性值,列表更改是从列表中删除项或向列表添加项。 因此,用于数据绑定的列表必须实现 IBindingList,它提供两种类型的更改通知。 BindingList<T> 是 IBindingList 的通用实现,旨在与 Windows 窗体数据绑定一起使用。 可以创建一个 BindingList,其中包含实现 INotifyPropertyChanged 的​​业务对象类型,并且该列表将自动将 PropertyChanged 事件转换为 ListChanged 事件。 如果绑定列表不是 IBindingList,必须使用 BindingSource 组件将对象列表绑定到 Windows 窗体控件。 BindingSource 组件将提供属性到列表的转换,该转换类似于 BindingList 的属性到列表的转换。 

3、自定义控件的更改通知

最后,在控件端,必须为每个旨在绑定到数据的属性公开一个 PropertyNameChanged 事件。 然后将对控件属性的更改传播到绑定的数据源。 

4、应用 PropertyNameChanged 模式

下面的代码示例演示如何将 PropertyNameChanged 模式应用于自定义控件。 在实现与 Windows 窗体数据绑定引擎一起使用的自定义控件时,请应用该模式。

// This class implements a simple user control
// that demonstrates how to apply the propertyNameChanged pattern.
[ComplexBindingProperties("DataSource", "DataMember")]
public class CustomerControl : UserControl
{
    private DataGridView dataGridView1;
    private Label label1;
    private DateTime lastUpdate = DateTime.Now;

    public EventHandler DataSourceChanged;

    public object DataSource
    {
        get
        {
            return this.dataGridView1.DataSource;
        }
        set
        {
            if (DataSource != value)
            {
                this.dataGridView1.DataSource = value;
                OnDataSourceChanged();
            }
        }
    }

    public string DataMember
    {
        get { return this.dataGridView1.DataMember; }

        set { this.dataGridView1.DataMember = value; }
    }

    private void OnDataSourceChanged()
    {
        if (DataSourceChanged != null)
        {
            DataSourceChanged(this, new EventArgs());
        }
    }

    public CustomerControl()
    {
        this.dataGridView1 = new System.Windows.Forms.DataGridView();
        this.label1 = new System.Windows.Forms.Label();
        this.dataGridView1.ColumnHeadersHeightSizeMode =
           System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
        this.dataGridView1.ImeMode = System.Windows.Forms.ImeMode.Disable;
        this.dataGridView1.Location = new System.Drawing.Point(100, 100);
        this.dataGridView1.Size = new System.Drawing.Size(500,500);
                    
        this.dataGridView1.TabIndex = 1;
        this.label1.AutoSize = true;
        this.label1.Location = new System.Drawing.Point(50, 50);
        this.label1.Name = "label1";
        this.label1.Size = new System.Drawing.Size(76, 13);
        this.label1.TabIndex = 2;
        this.label1.Text = "Customer List:";
        this.Controls.Add(this.label1);
        this.Controls.Add(this.dataGridView1);
        this.Size = new System.Drawing.Size(450, 250);
    }
}

5、实现 INotifyPropertyChanged 接口

下面的代码示例演示如何实现 INotifyPropertyChanged 接口。 在 Windows 窗体数据绑定中使用的业务对象上实现该接口。 实现时,该接口将业务对象上的属性更改与绑定控件进行通信。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Runtime.CompilerServices;
using System.Windows.Forms;

// Change the namespace to the project name.
namespace binding_control_example
{
    // This form demonstrates using a BindingSource to bind
    // a list to a DataGridView control. The list does not
    // raise change notifications. However the DemoCustomer1 type
    // in the list does.
    public partial class Form3 : Form
    {
        // This button causes the value of a list element to be changed.
        private Button changeItemBtn = new Button();

        // This DataGridView control displays the contents of the list.
        private DataGridView customersDataGridView = new DataGridView();

        // This BindingSource binds the list to the DataGridView control.
        private BindingSource customersBindingSource = new BindingSource();

        public Form3()
        {
            InitializeComponent();

            // Set up the "Change Item" button.
            this.changeItemBtn.Text = "Change Item";
            this.changeItemBtn.Dock = DockStyle.Bottom;
            this.changeItemBtn.Height = 100;
            //this.changeItemBtn.Click +=
              //  new EventHandler(changeItemBtn_Click);
            this.Controls.Add(this.changeItemBtn);

            // Set up the DataGridView.
            customersDataGridView.Dock = DockStyle.Top;
            this.Controls.Add(customersDataGridView);

            this.Size = new Size(400, 200);
        }

        private void Form3_Load(object sender, EventArgs e)
        {
            this.Top = 100;
            this.Left = 100;
            this.Height = 600;
            this.Width = 1000;

            // Create and populate the list of DemoCustomer objects
            // which will supply data to the DataGridView.
            BindingList<DemoCustomer1> customerList = new ();
            customerList.Add(DemoCustomer1.CreateNewCustomer());
            customerList.Add(DemoCustomer1.CreateNewCustomer());
            customerList.Add(DemoCustomer1.CreateNewCustomer());

            // Bind the list to the BindingSource.
            this.customersBindingSource.DataSource = customerList;

            // Attach the BindingSource to the DataGridView.
            this.customersDataGridView.DataSource =
                this.customersBindingSource;
        }

        // Change the value of the CompanyName property for the first
        // item in the list when the "Change Item" button is clicked.
        void changeItemBtn_Click(object sender, EventArgs e)
        {
            // Get a reference to the list from the BindingSource.
            BindingList<DemoCustomer1>? customerList =
                this.customersBindingSource.DataSource as BindingList<DemoCustomer1>;

            // Change the value of the CompanyName property for the
            // first item in the list.
            customerList[0].CustomerName = "Tailspin Toys";
            customerList[0].PhoneNumber = "(708)555-0150";
        }
                
    }

    // This is a simple customer class that
    // implements the IPropertyChange interface.
    public class DemoCustomer1 : INotifyPropertyChanged
    {
        // These fields hold the values for the public properties.
        private Guid idValue = Guid.NewGuid();
        private string customerNameValue = String.Empty;
        private string phoneNumberValue = String.Empty;

        public event PropertyChangedEventHandler PropertyChanged;

        // This method is called by the Set accessor of each property.
        // The CallerMemberName attribute that is applied to the optional propertyName
        // parameter causes the property name of the caller to be substituted as an argument.
        private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        // The constructor is private to enforce the factory pattern.
        private DemoCustomer1()
        {
            customerNameValue = "Customer";
            phoneNumberValue = "(312)555-0100";
        }

        // This is the public factory method.
        public static DemoCustomer1 CreateNewCustomer()
        {
            return new DemoCustomer1();
        }

        // This property represents an ID, suitable
        // for use as a primary key in a database.
        public Guid ID
        {
            get
            {
                return this.idValue;
            }
        }

        public string CustomerName
        {
            get
            {
                return this.customerNameValue;
            }

            set
            {
                if (value != this.customerNameValue)
                {
                    this.customerNameValue = value;
                    NotifyPropertyChanged();
                }
            }
        }

        public string PhoneNumber
        {
            get
            {
                return this.phoneNumberValue;
            }

            set
            {
                if (value != this.phoneNumberValue)
                {
                    this.phoneNumberValue = value;
                    NotifyPropertyChanged();
                }
            }
        }
    }
}

6、同步绑定

在 Windows 窗体中实现数据绑定期间,多个控件会绑定到同一数据源。 在某些情况下,可能需要采取额外的步骤来确保控件的绑定属性之间,以及它们和数据源之间保持同步。 在两种情况下,需要执行以下步骤:

  • 数据源未实现 IBindingList,因此生成类型为 ItemChanged 的 ListChanged 事件。

  • 数据源实现了 IEditableObject。

在前一种情况下,请使用 BindingSource 将数据源绑定到控件。 在后一种情况下,请使用 BindingSource 并处理 BindingComplete 事件,然后在相关的 BindingManagerBase 上调用 EndCurrentEdit。文章来源地址https://www.toymoban.com/news/detail-775690.html

到了这里,关于【WinForm.NET开发】设计具有更改通知的出色数据源的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包赞助服务器费用

相关文章

  • 设计一个AI Faas API 系统,支持自然语言生成SQL,并查询数据源数据返回表数据,API开发完成即可线上使用

    设计一个AI Faas API 系统,支持自然语言生成SQL,并查询数据源数据返回表数据,API开发完成即可线上使用

    设计一个AI Faas API 系统,支持自然语言生成SQL,并查询数据源数据返回表数据。同时,支持API开发完成即可线上使用。给我详细系统设计说明和完整的Golang代码,解释说明。5000字以上。 An AI Faas API system is designed to support Natural language generation to generate SQL, query data source data and

    2024年02月07日
    浏览(16)
  • Winform中DataGridView设置前景色、单元格背景色、标题栏样式、禁止改变高宽、不显示空白行、清除选中样式、填充数据源、设置标题、设置单列宽度

    Winform中DataGridView设置前景色、单元格背景色、标题栏样式、禁止改变高宽、不显示空白行、清除选中样式、填充数据源、设置标题、设置单列宽度

    Winform中使用DataGridView实现加载数据并显示在led大屏中。 需要设置整个DataGridView的前景色、背景色、单元格颜色、标题栏样式、禁止 改变行高、列宽、不显示新增行、取消选中样式等。 注: 博客: 霸道流氓气质的博客_CSDN博客-C#,架构之路,SpringBoot领域博主 1、DateGridView实现黑

    2023年04月15日
    浏览(50)
  • WPF基础入门-Class6-WPF通知更改

    WPF基础入门-Class6-WPF通知更改

    Class6-WPF通知 1、显示页面: 页面cs文件: 2、新建一个 ViewModelBase.cs 文件 3、model文件:其中定义的 Name 和 Title 与 xaml文件 中控件绑定一致 运行效果:

    2024年02月11日
    浏览(11)
  • 关闭 Windows 安全中心警报 及 用户账户允许此应用对你的设备进行更改 通知 及 打开文件 - 安全警告 通知

    关闭 Windows 安全中心警报 及 用户账户允许此应用对你的设备进行更改 通知 及 打开文件 - 安全警告 通知

    目录 1.关闭 Windows 安全中心警报 2.关闭 用户账户 允许此应用对你的设备进行更改 通知 3.关闭 打开文件 - 安全警告 通知 打开控制面板 :Win + R 打开运行 输入 control     取消勾选即可 。  打开控制面板 :Win + R 打开运行 输入 control      打开控制面板 :Win + R 打开运行 输入

    2024年02月11日
    浏览(9)
  • WinForm界面程序 多语言切换[.Net 6.0]

    WinForm界面程序 多语言切换[.Net 6.0]

    开发环境:VS2022 社区版 中文界面 .Net 6.0 WinForm界面程序 创建窗体,并添加几个按钮;添加切换语言的RadioButton; 修改窗体的Localizable属性为True 修改窗体的Language属性为’英语(美国)\\\',修改按钮文本 编译生成工程 检查解决方案资源管理器的Form1.cs下面是否生成Form1.en-US.resx文件 建议不

    2024年02月06日
    浏览(11)
  • ReaLTaiizor开源.NET winform控件库学习使用

    ReaLTaiizor开源.NET winform控件库学习使用

    基于MIT license开源、免费、美观的.NET WinForm UI控件库:ReaLTaiizor ReaLTaiizor 是一个开源免费的.NET WinForms控件库,它提供了广泛的组件和丰富的主题选项(用户友好、注重设计),让用户可以轻松创建美观、专业的桌面应用程序。 WinForm 是一个传统的桌面应用程序框架,它基于

    2024年04月16日
    浏览(6)
  • net6 winform使用依赖注入(IOC)

    net6 winform使用依赖注入(IOC)

    依赖注入(DI)是一种设计模式,它可以消除编程代码之间的依赖性,因此可以很容易地管理和测试应用程序。它有三种类型分别为构造函数注入,属性注入以及方法注入。它具有减少依赖性增强组件的可重用性等好处。 通俗的来说我们不通过 new 的方式在类内部创建依赖类

    2024年02月05日
    浏览(10)
  • U8 内嵌.Net UserControl,winform挂菜单

    U8 内嵌.Net UserControl,winform挂菜单

    创建类库命名:UFIDA.U8.Portal.+自定义名称… F: U8SOFTInteropInterop.U8Login.dll //设置嵌入互操作类型为false F: U8SOFTInteropInterop.UFPortalProxylnterface.dll F: U8SOFTPortal UFIDA.U8.Portal.Common.dll F: U8SOFTPortalUFIDA.U8.Portal.Framework.dll F: U8SOFTPortal UFIDA.U8.Portal.Proxy.dll F: U8SOFTFrameworkUFSoft.U8.Framewor

    2024年01月21日
    浏览(10)
  • 『EasyNotice』.NET开源消息通知组件——快速实现邮件/钉钉/飞书/企业微信告警通知

    『EasyNotice』.NET开源消息通知组件——快速实现邮件/钉钉/飞书/企业微信告警通知

    📣读完这篇文章里你能收获到 了解博主开源的告警通知项目——EasyNotice 傻瓜式扩展方法直接使用 如何通过EasyNotice快速实现邮件/钉钉/飞书/企业微信的通知发送 感谢点赞+收藏,避免下次找不到~ 这是博主开源的一个基于.NET开源的消息通知组件,它包含了邮件、钉钉、飞书

    2023年04月08日
    浏览(13)
  • Log4net在.Net Winform项目中的使用

    Log4net在.Net Winform项目中的使用

    Log4net是一个流行的日志记录工具,可以帮助开发人员在应用程序中实现高效的日志记录。本文将提供一个详细的分步骤示例,来帮助您在.Net Winform项目中使用Log4net。 打开Visual Studio工具。 选择您的.Net Winform项目,并右击选择“管理NuGet程序包”。 在NuGet程序包管理器中搜索并

    2024年02月12日
    浏览(13)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包