【问题标题】:Has the DataSource been changed via a BindingSource?DataSource 是否已通过 BindingSource 更改?
【发布时间】:2013-10-07 22:07:51
【问题描述】:

我正在使用 BindingSource 将单个大型数据结构连接到多个控件(没有 SQL,只有一个数据结构,多个控件)。旧式 Windows 窗体应用程序,Visual Studio 2012 Express。我已经设法用属性包装了许多 GUI 组件,以解决缺乏对诸如单选按钮组、多选列表框、标题栏等内容的控件绑定的直接支持的问题。所有这些都很好,更新在两个方向上都很好地流动在 GUI 和数据结构之间。

我需要跟踪 任何 数据结构的更改是否已通过 GUI 上的任何控件进行,但我不知道如何执行此操作(我确实在这里查看了以前的相关问题)...这需要提供“已进行但未保存的更改”的简单指示,标题栏中带有星号,如果用户尝试退出应用程序而不保存更改,则会发出警告.

提前感谢您的帮助!

【问题讨论】:

  • WPF ? ASP ? Winforms?
  • 抱歉,旧式 Windows 窗体

标签: c# datasource bindingsource


【解决方案1】:

您必须在您的对象类中实现 INotifyPropertyChanged 接口,然后通过您的 DataSource BindingSource 属性中的类型类的适当事件处理程序捕获发生更改的任何时间。

这是一个例子:

using System;
using System.ComponentModel;

namespace ConsoleApplication1
{
    internal class Program
    {
        class Notifications
        {
            static void Main(string[] args)
            {
                var daveNadler = new Person {Name = "Dave"};
                daveNadler.PropertyChanged += PersonChanged;
            }

            static void PersonChanged(object sender, PropertyChangedEventArgs e)
            {
                Console.WriteLine("Something changed!");
                Console.WriteLine(e.PropertyName);
            }
        }
    }

    public class Person : INotifyPropertyChanged
    {
        private string _name = string.Empty;
        private string _lastName = string.Empty;
        private string _address = string.Empty;

        public string Name
        {
            get { return this._name; }
            set
            {
                this._name = value;
                NotifyPropertyChanged("Name");
            }
        }

        public string LastName
        {
            get { return this._lastName; }
            set
            {
                this._lastName = value;
                NotifyPropertyChanged("LastName");
            }
        }

        public string Address
        {
            get { return this._address; }
            set
            {
                this._address = value;
                NotifyPropertyChanged("Address");
            }
        }


        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged(string info)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }
    }
}

【讨论】:

  • 也许我误解了文档 - 我认为这仅适用于绑定列表中当前选定的项目???
  • 另外,文档似乎说这个事件是关于元数据的,而不是内容?我误解了文档吗??
  • @DaveNadler - 我误解了你在找什么。这是一个如何使用 INotifyPropertyChanged 接口的示例。如果您像这样连接它,您应该不会检测到属性更改并保存相关属性。
  • BindingSource 避免了必须为我的数据结构中的每个属性编写显式通知处理。我正在寻找一种方法来简单地捕获通过 BindingSource 发布的任何更改,而无需修改单个数据结构中的每个属性...
  • 将 INotifyPropertyChanged 接口添加到数据结构的类定义会导致 binder 停止工作(并且永远不会调用 notify 方法)...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-15
  • 2010-10-03
  • 2017-05-23
  • 1970-01-01
  • 2010-11-23
  • 2023-03-24
相关资源
最近更新 更多