App.xaml.cs 中的 WPF 全局事件处理程序

WPF global event handler in App.xaml.cs

您好,我们将处理事件 OnPropertyChanged 并获取该变量在所有应用程序表单中的值。

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 - 
}

如何触发此事件 "OnPropertyChanged" 并在所有 App windows.

上获取值 Connected

从表面上看,这看起来就像每个表单调用一样简单

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

并在您的处理程序中使用

(sender as App).Connected

获取 属性 的值。