简体   繁体   中英

How to create a custom event when a property is changed?

I've created a my own class, which has public properties of the double data type X and Y, when one of these gets changed I want an event to fire which will be used to update the position of visual object like a canvas or something. I've been searching for answers online and I don't really understand how to properly do it. I'm new to programming and I've seen people mention INotifyPropertyChanged, but I don't know how to use it or where to put things.

I want an event to occur when X or Y get changed which I can attach a method to.. please help

Inside your view model class, in the setters of your X and Y properties you could call your update method:

    public double X
    {
        get
        {
            return x;
        }
        set
        {
            if (value != x)
            {
                x= value;
                OnPropertyChanged("X");
                VisualObjectUpdateMethod();
            }
        }
    }
    private double x;

The logic to update whatever you want to update would then be located in the VisualObjectUpdateMethod.

If whatever you want to do is part of the same class, you can just use the setter:

public class Something
{
    private string _Message;
    public string Message
    {
        get { return _Message;
        set
        {
            if (_Message != value)
            {
                _Message = value;
                CallSomeMethod();
            }
        }
    }

    public void CallSomeMethod()
    {
        Debug.WriteLine("Message is now: " + Message);
    }
}

You need to learn Delegates and Events

MSDN also has an example which is pretty much what you are asking

From the same page this is the relevant section;

    public void Update(double d)
    {
        radius = d;
        area = 3.14 * radius * radius;
        OnShapeChanged(new ShapeEventArgs(area));
    }
    protected override void OnShapeChanged(ShapeEventArgs e)
    {
        // Do any circle-specific processing here.

        // Call the base class event invocation method.
        base.OnShapeChanged(e);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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