开发者

responding to the model's property changes in asp.net mvc2

开发者 https://www.devze.com 2023-03-05 06:23 出处:网络
I am havi开发者_运维技巧ng a model not in EF, but in plain text. I have to have the updated events handled for each of the model\'s properties so that i can log their changes.

I am havi开发者_运维技巧ng a model not in EF, but in plain text. I have to have the updated events handled for each of the model's properties so that i can log their changes.

Is there a way for this to be achieved.


Implement the INotifyPropertyChanged interface.

A simple example:

using System.ComponentModel;

public class MyModel : INotifyPropertyChanged
{
    string _myProperty;

    public event PropertyChangedEventHandler PropertyChanged;

    public string MyProperty
    {
        get { return _myProperty; }
        set 
        { 
            _myProperty = value;
            NotifyPropertyChanged("MyProperty");
        }
    }

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

You can use it like...

public class Test
{
    public static void Main()
    {
        var model = new MyModel();
        model.PropertyChanged += new PropertyChangedEventHandler(LogChange);

        model.MyProperty="apples";
        model.MyProperty="oranges";
        model.MyProperty="pears";
    }

    public static void LogChange(object sender, PropertyChangedEventArgs args)
    {
        Console.WriteLine(args.PropertyName + " has changed!");
        Console.WriteLine("New value: " 
                   + sender.GetType().GetProperty(args.PropertyName)
                     .GetValue(sender, null));
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消