Why does Application.Current == null in a WinForms application?

前端 未结 3 1177
日久生厌
日久生厌 2020-12-10 12:27

Why does Application.Current come out to null in a WinForms application? How and when is it supposed to be set?

I am doing:

 static clas         


        
相关标签:
3条回答
  • 2020-12-10 12:54

    Based on this other SO question, Application.Current is a WPF feature and not a WinForm feature.

    Application.Current Question

    There is an MSDN post that shows how to leverage the feature in Winform by adding some references to your code:

    you can add a reference to PresentationFramework first:

    1.In Solution Explorer, right-click the project node and click Add Reference.

    2.In the Add Reference dialog box, select the .NET tab.

    3.Select the PresentationFramework, and then click OK.

    4.Add "using System.Windows.Shell;" and "using System.Windows;" to your code.

    0 讨论(0)
  • 2020-12-10 12:55

    Application.Current is Specific for WPF Application. Therefore when you are using WPF controls in WinForms Application you need to initialize instance of WPF Application. Do this in your WinForms Application.

    if ( null == System.Windows.Application.Current )
    {
       new System.Windows.Application();
    } 
    
    0 讨论(0)
  • 2020-12-10 12:58

    Well IMHO opinion the other SO answer is not really the way to go for windows forms, although maybe not incorrect.

    Normally you would use ISynchronizeInvoke for such a feature in WinForms. Every container control implements this interface.

    You'll need to BeginInvoke() method to marshall the call back to the proper thread.

    Based on your previous question the code would become:

    public class SomeObject : INotifyPropertyChanged
    {
        private readonly ISynchronizeInvoke invoker;
        public SomeObject(ISynchronizeInvoke invoker)
        {
            this.invoker = invoker;
        }
    
        public decimal AlertLevel
        {
            get { return alertLevel; }
            set
            {
                if (alertLevel == value) return;
                alertLevel = value;
                OnPropertyChanged("AlertLevel");
            }
        }
    
        private void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                this.invoker.BeginInvoke((Action)(() =>
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName))), null);
    
            }
        }
    }
    

    Where you pass the owning Form class to the constructor of SomeObject. The PropertyChanged will now raised on the UI thread of the owning form class.

    0 讨论(0)
提交回复
热议问题