Simple small INotifyPropertyChanged implementation

后端 未结 6 1521
深忆病人
深忆病人 2021-01-06 07:51

Say I have the following class:

public MainFormViewModel
{
    public String StatusText {get; set;}
}

What is the easiest smallest way to g

6条回答
  •  感情败类
    2021-01-06 08:06

    I have a base class called "Model". It exposes a protected object called DataPoints, which is essentially a dictionary.

    C#

    public String StatusText {
        get { 
            return (string)DataPoints["StatusText"]; 
        } 
        set { 
            DataPoints["StatusText"] = value; 
        }
    }
    

    VB

    public Property StatusText as String 
        get 
            return DataPoints!StatusText 
        end get 
        set
            DataPoints!StatusText = value
        end set
    end property
    

    When you set a value in the DataPoints dictionary it does the following:

    1. Checks to make sure the value actually changed.
    2. Saves the new value
    3. Sets the IsDirty property to true.
    4. Raises the Property Changed event for the named property as well as the IsDirty and IsValid properties.

    Since it is a dictionary, it also makes loading objects from a database or XML file really easy.

    Now you may think reading and writing to dictionary is expensive, but I've been doing a lot of performance testing and I haven't found any noticable impact from this in my WPF applications.

提交回复
热议问题