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

Why is Application.Current going null in a WinForms application? How and when should it be installed?

I do:

  static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.Run(new MainForm()); } } 
+7
c # winforms
source share
3 answers

Application.Current is specific to WPF application. Therefore, when you use WPF controls in a WinForms application, you need to initialize the instance of the WPF application. Do this in your WinForms application.

 if ( null == System.Windows.Application.Current ) { new System.Windows.Application(); } 
+13
source share

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

Application.Current Question

There is an MSDN message that shows how to use a function in Winform by adding some links to your code:

you can first add a link to the PresentationFramework:

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

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

3. Select "View" and click "OK."

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

+2
source share

Good opinion IMHO, another SO answer is actually not the way for window forms, although it may be wrong.

Usually you use ISynchronizeInvoke for such a function in WinForms. Each container control implements this interface.

You will need the BeginInvoke() method to transfer the call back to the appropriate stream.

For your previous question, the code would look like this:

 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 your own Form class to the SomeObject constructor. PropertyChanged will now be added to the custom form class UI thread.

+1
source share

All Articles