Share:

Custom Event In C# WPF | Saatody | Amit Padhiyar

 Today I will talk about... How to create custom event in C# WPF. First, We need a class which can contains our properties and events.

private double x = 0.0;
public double X
{
    set
    {
        x = value;
        OnValueChanged(EventArgs.Empty);
    }
    get
    {
        return x;
    }
}

Here, We have a property in A class. Where OnValueChanged() is protected event method within A class. Follow below code.

public EventHandler ValueChanged;
protected virtual void OnValueChanged(EventArgs e)
{
    EventHandler handler = ValueChanged;
    if (handler != null)
    {
        handler(this, e);
    }
}

Now we invented new event which name is ValueChanged. You can use this event as normal event in other class(es). For example B class. Follow below code.

BClass.ValueChanged += (sender, e) =>
{
    System.Console.WriteLine("X: " + BClass.X);
};

This how we created ValueChanged custom event in C# WPF.

Note: Always use 'event' keyword before EventHandler.
This how compiler can better understand.

 Example:

public EventHandler ValueChanged;
public event EventHandler ValueChanged; 

 

Comments

Popular posts from this blog

Get Color From Pixel C# WPF | Saatody | Amit Padhiyar

Basic Audio Operations With MP3 And Wave Files Using NAudio C#

Create Drag And Drop Operation Between DevExpress GridControl And Custom WPF UI | Saatody | Amit Padhiyar