繁体   English   中英

如何实现INotifyPropertyChanged

[英]How to implement INotifyPropertyChanged

我需要在自己的数据结构类中实现INotifyPropertyChanged的帮助。 这是用于类分配的,但是实现INotifyPropertyChanged是我正在做的事情,超出了规则的要求。

我有一个名为“ BusinessRules”的类,该类使用SortedDictionary来存储“员工”类型的对象。 我有一个显示所有员工的DataGridView,并且我想将BusinessRules类对象用作DataGridView的数据源。 分配需要BusinessRules容器。 我试图在此类中实现INotifyPropertyChanged,但没有成功。

我正在使用的数据源是一个BindingList。 目前,我将那个BindingList用作“ sidecar”容器,并将其设置为我的DataSource。 我对BusinessRules类对象所做的每个更改都将镜像到我的BindingList类对象。 但这显然是草率的编程,我想做得更好。

我试图在BusinessRules中实现INotifyPropertyChanged,但是当我将实例化的BusinessRules对象设置为DataSource时,DataGridView什么都没有显示。 我怀疑问题是出在NotifyPropertyChanged()方法上。 我不知道该如何传递,也不知道该如何传递。大多数示例都涉及更改名称,但是当将新对象添加到SortedDictionary中时,我更担心。

    private void NotifyPropertyChanged( Employee emp )
    {
        PropertyChanged?.Invoke( this, new PropertyChangedEventArgs( emp.FirstName ) );
    }

我需要更改什么才能使它正常工作? 您能解释一下为什么我的尝试无效吗?

我对在StackOverflow上提出问题感到很不好。 这不是故意的。 请让我知道您还需要什么其他信息,我们将尽快提供。

这是我的BusinessRules源代码的链接

如果您阅读有关如何实现MVVM的教程,这将非常有帮助。

您需要一个实现INotifyPropertyChanged接口的基类。 因此,所有视图模型都应从该基类继承。

public class ViewModelBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected void RaisePropertyChangedEvent(string propertyName)
    {
        var handler = PropertyChanged;
        if (handler != null)
            handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

// This sample class DelegateCommand is used if you wanna bind an event action with your view model
public class DelegateCommand : ICommand
{
    private readonly Action _action;

    public DelegateCommand(Action action)
    {
        _action = action;
    }

    public void Execute(object parameter)
    {
        _action();
    }

    public bool CanExecute(object parameter)
    {
        return true;
    }

#pragma warning disable 67
    public event EventHandler CanExecuteChanged;
#pragma warning restore 67
}

您的视图模型应如下所示。

public sealed class BusinessRules : ViewModelBase

这是有关如何使用RaisePropertyChangedEvent

public sealed class Foo : ViewModelBase
{
    private Employee employee = new Employee();

    private string Name
    {
        get { return employee.Name; }
        set 
        { 
            employee.Name = value; 
            RaisePropertyChangedEvent("Name"); 
            // This will let the View know that the Name property has updated
        }
    }

    // Add more properties

    // Bind the button Command event to NewName
    public ICommand NewName
    {
        get { return new DelegateCommand(ChangeName)}
    }

    private void ChangeName()
    {
        // do something
        this.Name = "NEW NAME"; 
        // The view will automatically update since the Name setter raises the property changed event
    }
}

我真的不知道您想做什么,所以我将像这样保留我的示例。 最好阅读不同的教程,学习曲线有点陡峭。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM