【问题标题】:WPF global event handler in App.xaml.csApp.xaml.cs 中的 WPF 全局事件处理程序
【发布时间】:2018-04-26 21:29:47
【问题描述】:

您好,我们将处理 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 的窗口上获取 Connected 值。

【问题讨论】:

  • 我不建议在这种情况下使用 on property change,您可能想创建自定义事件并订阅它。

标签: c# wpf code-behind


【解决方案1】:

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

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

在你的处理程序中,使用

(sender as App).Connected

获取该属性的值。

【讨论】:

  • 我的情况并不复杂,就像我的帖子中解释的那样。这适用于事件,但我怎样才能检索 Connected Property 的值?例如:'公共部分类 MainWindow : Window { public MainWindow() { InitializeComponent(); GridRoot.DataContext = 这个; (Application.Current as App).PropertyChanged += MainWindow_PropertyChanged;} private void MainWindow_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) {Button.Content = "status : " + App.Current.Properties["Connected"];} }'
  • sender 是应用程序本身,它是引发事件的实例。就做(sender as App).Connected
猜你喜欢
  • 1970-01-01
  • 2012-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-26
  • 2015-04-05
  • 1970-01-01
相关资源
最近更新 更多