Search code examples
c#wpfeventsdependency-propertiesdelegation

Create event for variable in WPF


I have a WPF form with a start button. When it is clicked, I'm calling the start function of another class called ClassA.

Here's the code for ClassA:

    private DispatcherTimer m_dispatcherTimer = new DispatcherTimer();
    private int m_timerCounter;

    public bool IsRunning { get; private set; }

    private void DispatcherTimer_Tick(object sender, EventArgs e)
    {
        m_timerCounter ++;

        if (m_timerCounter == MaxCounter)
            Stop();
    }

    public void Start()
    {
        IsRunning = true;
        m_timerCounter = 0;
        m_dispatcherTimer.Start();
    }

    public void Stop()
    {
        m_dispatcherTimer.Stop();
        m_timerCounter = 0;
        IsRunning = false;
    }

Here's what I'm after:

I would like to pop up a message box in the form's code behind, whenever the property IsRunning of ClassA changes.

I could monitor it using a while loop and put it in a thread, but I would like to avoid it.


Solution

  • You create an event like this:

    //globals in ClassA
    //create the handler delegate
    public delegate void RunningChanged(bool isRunning);
    //create the event
    public event RunningChanged OnRunningChanged;
    

    Invoke it:

    //method in ClassA
    private void SetRunning(bool running) 
    {
        IsRunning = running;
        var handler = OnRunningChanged;
        if (handler != null)
        {
            handler(running);
        }
    }
    

    So in your forms code behind you can do something like:

    var instance = new ClassA();
    instance.OnRunningChanged += OnRunningChangedHandler;
    
    private void OnRunningChangedHandler(bool isRunning)
    {
         //do whatever you want to do when th running property changes
    }