无法访问在同一类中声明的类实例
本文关键字:一类 声明 实例 访问 | 更新日期: 2023-09-27 18:31:54
>我有一个首选项窗口,需要检测它是否打开。如果它是打开的,我就会关闭它。它关闭了,我打开了它。我在类中声明了一个类实例,以便我可以在使用 if 语句的情况下访问它。当我尝试访问它时,似乎我不能。在这种情况下,我无法访问_prefsForm。这是 MVVM。
这是代码:
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;
}
您不需要保留对打开的Window
对象的引用。您可以像这样访问打开的Window
:
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();
如果您只有以下Window
之一,则使用Linq
会更容易:
using System.Linq;
using Views.Dialogs;
...
Preferences preferencesWindow =
Application.Current.Windows.OfType<Preferences>().First();
实际上,即使您有多个以下Window
,使用 Linq
也会更容易:
using System.Linq;
using Views.Dialogs;
...
Preferences preferencesWindow = Application.Current.Windows.OfType<Preferences>().
Where(w => w.Name = NameOfYourWindow).First();