[英]How do I know if a WPF window is opened
在 WPF 窗口中,如何知道它是否已打開?
我的目標是當時只打開 1 個窗口實例。
所以,我在父窗口中的偽代碼是:
if (this.m_myWindow != null)
{
if (this.m_myWindow.ISOPENED) return;
}
this.m_myWindow = new MyWindow();
this.m_myWindow.Show();
編輯:
我找到了解決我最初問題的解決方案。 window.ShowDialog();
它阻止用戶打開任何其他窗口,就像模式彈出窗口一樣。 使用此命令,無需檢查窗口是否已打開。
在WPF
中, Application
類中有一個打開Windows
的集合,您可以創建一個輔助方法來檢查窗口是否打開。
這是一個示例,將檢查是否有某種Type
任何Window
或具有特定名稱的Window
是否已打開,或兩者都打開。
public static bool IsWindowOpen<T>(string name = "") where T : Window
{
return string.IsNullOrEmpty(name)
? Application.Current.Windows.OfType<T>().Any()
: Application.Current.Windows.OfType<T>().Any(w => w.Name.Equals(name));
}
用法:
if (Helpers.IsWindowOpen<Window>("MyWindowName"))
{
// MyWindowName is open
}
if (Helpers.IsWindowOpen<MyCustomWindowType>())
{
// There is a MyCustomWindowType window open
}
if (Helpers.IsWindowOpen<MyCustomWindowType>("CustomWindowName"))
{
// There is a MyCustomWindowType window named CustomWindowName open
}
您可以檢查m_myWindow==null
是否然后創建並顯示窗口。 當窗口關閉時,將變量設置回 null。
if (this.m_myWindow == null)
{
this.m_myWindow = new MyWindow();
this.m_myWindow.Closed += (sender, args) => this.m_myWindow = null;
this.m_myWindow.Show();
}
這是使用 LINQ 實現此目的的另一種方法。
using System.Linq;
...
public static bool IsOpen(this Window window)
{
return Application.Current.Windows.Cast<Window>().Any(x => x == window);
}
用法:
bool isOpen = myWindow.IsOpen();
如果發現需要激活窗口,可以使用下面的代碼:
//activate a window found
//T = Window
Window wnd = Application.Current.Windows.OfType<T>().Where(w => w.Name.Equals(nome)).FirstOrDefault();
wnd.Activate();
在你的類中放置一個靜態布爾值,命名為_open
或類似的東西。 在構造函數中然后執行以下操作:
if (_open)
{
throw new InvalidOperationException("Window already open");
}
_open = true;
並在 Closed 事件中:
_open = false;
是你搜索嗎?
if (this.m_myWindow != null)
{
if (this.m_myWindow.IsActive) return;
}
this.m_myWindow = new MyWindow();
this.m_myWindow.Show();
如果你想要一個單例,你應該閱讀這個: 我們如何為一個窗口創建一個單例實例?
void pencereac<T> (int Ops) where T : Window , new()
{
if (!Application.Current.Windows.OfType<T>().Any()) // Check is Not Open, Open it.
{
var wind = new T();
switch (Ops)
{
case 1:
wind.ShowDialog();
break;
case 0:
wind.Show();
break;
}
}
else Application.Current.Windows.OfType<T>().First().Activate(); // Is Open Activate it.
}
庫拉尼米:
void Button_1_Click(object sender, RoutedEventArgs e)
{
pencereac<YourWindow>(1);
}
如果您想檢查第二個表單是否已經打開並避免在按鈕單擊時再次打開它,這將起作用。
int formcheck = 0;
private void button_click()
{
Form2Name myForm2 = new Form2Name();
if(formcheck == 0)
{
myForm2.Show(); //Open Form2 only if its not active and formcheck == 0
// Do Somethin
formcheck = 1; //Set it to 1 indicating that Form2 have been opened
{
{
public bool IsWindowOpen<T>(string name = "") where T : Window
{
return Application.Current.Windows.OfType<T>().Any(w => w.GetType().Name.Equals(name));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.