簡體   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