如何实现INotifyPropertyChanged

时间:2016-10-12 05:20:06

标签: c# datagridview inotifypropertychanged

我需要帮助在我自己的数据结构类中实现INotifyPropertyChanged。这是一个类赋值,但实现INotifyPropertyChanged是我在上面做的一个补充,超出了量规要求。

我有一个名为' BusinessRules'它使用SortedDictionary来存储' Employee'类型。我有一个DataGridView显示我的所有员工,我想使用我的BusinessRules类对象作为我的DataGridView的DataSource。分配需要BusinessRules容器。我试图在这个类中实现INotifyPropertyChanged,但没有成功。

我工作的DataSource是一个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上形成我的问题。这不是故意的。请告诉我您需要的其他信息,我会尽快提供。

Here is a link to my BusinessRules source code

1 个答案:

答案 0 :(得分:2)

如果您阅读how to implement 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
    }
}

我真的不知道你想做什么,所以我会留下这样的例子。更好地阅读不同的教程,学习曲线有点陡峭。