为什么WinForms应用程序中的Application.Current == null?
为什么Application.Current
在WinForms应用Application.Current
出现null? 应该如何以及何时设置?
我在做:
static class Program { /// /// The main entry point for the application. /// [STAThread] static void Main() { Application.Run(new MainForm()); } }
Application.Current特定于WPF应用程序。 因此,当您在WinForms应用程序中使用WPF控件时,您需要初始化WPF应用程序的实例。 在您的WinForms应用程序中执行此操作。
if ( null == System.Windows.Application.Current ) { new System.Windows.Application(); }
基于这个其他SO问题,Application.Current是一个WPFfunction而不是WinFormfunction。
Application.Current Question
有一篇MSDNpost通过添加对代码的一些引用来展示如何利用Winform中的function:
您可以先添加对PresentationFramework的引用:
1.在解决方案资源管理器中,右键单击项目节点,然后单击添加引用。
2.在“添加引用”对话框中,选择“.NET”选项卡。
3.选择PresentationFramework,然后单击“确定”。
4.添加“using System.Windows.Shell;” 和“使用System.Windows;” 你的代码。
恕我直言,其他SO的答案并不是真正的Windows窗体的方式,虽然可能不正确。
通常,您将在WinForms中使用ISynchronizeInvoke
来实现此类function。 每个容器控件都实现此接口。
您需要使用BeginInvoke()
方法将调用编组回适当的线程。
根据您之前的问题,代码将变为:
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); } } }
将拥有的Form
类传递给SomeObject
的构造函数的SomeObject
。 现在,PropertyChanged将在拥有的表单类的UI线程上引发。