C# Can';t访问在同一类中声明的类实例
我有一个首选项窗口,需要检测它是否打开。如果它是打开的,我就把它关上。它是关着的,我打开它。我在类中声明了一个类实例,以便在使用if语句的情况下访问它。当我试图访问它时,似乎无法访问。我无法访问案例中的预窗体。这是MVVM 代码如下:C# Can';t访问在同一类中声明的类实例,c#,wpf,mvvm,C#,Wpf,Mvvm,我有一个首选项窗口,需要检测它是否打开。如果它是打开的,我就把它关上。它是关着的,我打开它。我在类中声明了一个类实例,以便在使用if语句的情况下访问它。当我试图访问它时,似乎无法访问。我无法访问案例中的预窗体。这是MVVM 代码如下: Private Views.Dialogs.Preferences _prefsForm; .... case 4: if (_prefsForm == null)
Private Views.Dialogs.Preferences _prefsForm;
....
case 4:
if (_prefsForm == null)
{
_prefsForm = new Views.Dialogs.Preferences();
wih = new WindowInteropHelper(_prefsForm);
wih.Owner = hwnd;
_prefsForm.Show();
_editorState = EditorState.DISPLAYPREFS;
}
else
{
_prefsForm.Hide();
_editorState = EditorState.VIEWDATA;
_prefsForm = null;
}
break;
}
您不需要保留对打开的
窗口
对象的引用。您可以如下方式访问打开的窗口
:
Views.Dialogs.Preferences preferencesWindow = null;
foreach (Window window in Application.Current.Windows)
{
if (window is Views.Dialogs.Preferences)
{
preferencesWindow = (Views.Dialogs.Preferences)window;
break;
}
}
if (preferencesWindow.Visiblity == Visibility.Visible) preferencesWindow.Hide();
else preferencesWindow.Show();
如果您只有一个窗口
s,那么使用Linq
就更容易了:
using System.Linq;
using Views.Dialogs;
...
Preferences preferencesWindow =
Application.Current.Windows.OfType<Preferences>().First();
这是问题中的输入错误还是您有两个变量:
prefsForm
和\u prefsForm
?请详细说明“无法访问”“这是MVVM”的含义。。。恐怕不行。。。请严肃地告诉我们您得到的确切异常情况,变量是否已初始化?这肯定是重复的,否(即“对象引用未设置为对象的实例”,等等)?
using System.Linq;
using Views.Dialogs;
...
Preferences preferencesWindow = Application.Current.Windows.OfType<Preferences>().
Where(w => w.Name = NameOfYourWindow).First();