0

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

svick
  • 236,525
  • 50
  • 385
  • 514

3 Answers3

0

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.

KodeKreachor
  • 8,852
  • 10
  • 47
  • 64
0

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);
    }
}
John
  • 6,503
  • 3
  • 37
  • 58
  • it is not part of the same class, that's why I need an event to fire which i can use to trigger a change in another class – Windsurfer25 Mar 11 '12 at 03:41
  • @Windsurfer25 might want to use this then: http://stackoverflow.com/questions/6644247/simple-custom-event-c-sharp – John Mar 11 '12 at 05:07
0

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);
    }
Fahim Parkar
  • 30,974
  • 45
  • 160
  • 276
Master Chief
  • 2,520
  • 19
  • 28