Search code examples
c#wpfcode-behind

WPF global event handler in App.xaml.cs


Hi we would to handler the event OnPropertyChanged and gets the value in all application forms of this variable.

using System;
using System.ComponentModel;
using System.Windows; 
public partial class App : INotifyPropertyChanged
{

    #region - Connected -
    /// <summary>
    /// Gets or sets Connected status
    /// </summary>
    private Boolean connected = false;
    public Boolean Connected
    {
        get { return connected; }
        set
        {
            if(connected != value)
            {
                connected = value;
                OnPropertyChanged("Connected");
            }
        }
    }       
    #endregion - Connected -


    #region - INotifyPropertyChanged implementation -
    // Basically, the UI thread subscribes to this event and update the binding if the received Property Name correspond to the Binding Path element
    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
    #endregion - INotifyPropertyChanged implementation - 
}

how can fired this event "OnPropertyChanged" and get the value Connected On all App's windows.


Solution

  • On the surface, this looks as simple as each form calling

    (Application.Current as App).PropertyChanged += ....
    

    And in your handler, use

    (sender as App).Connected
    

    to get the value of that property.