事件触发器(按钮)打开同一窗口的多个实例
在我的 WPF 应用程序中,我有一个主窗口 (Branch.xaml),其中有一个按钮可打开另一个窗口 (Location.xaml)。打开此位置窗口后,当用户再次单击同一按钮时,如何防止打开此位置窗口的另一个实例?
或者,当用户再次单击该按钮时,如何重新聚焦同一个打开的窗口?
按钮单击代码是当您双击 xaml 中的按钮时自动生成的代码。
在“Branch.xaml.cs”文件中,按钮单击的代码如下:
private void rbtn_Location_Click(object sender, RoutedEventArgs e)
{
Location location = new Location();
location.Show();
}
Location 是一个自定义类,它打开一个带有 3 个列表框的窗口
谢谢,任何帮助都是值得赞赏的。 我正在 C# 4.0 上使用 WPF 应用程序视觉工作室 2010。
In my WPF application, I have a main window (Branch.xaml) which has a button that will open an other window (Location.xaml). Once this Location window is open, how do I prevent another instance of this Location window from opening, when the user clicks the same button again?
Or how can I re-focus the same open window, when the user clicks the button again?
The button click code is auto-generated code when you double-click on a button in xaml.
In the "Branch.xaml.cs" file, the code for button click is as follows:
private void rbtn_Location_Click(object sender, RoutedEventArgs e)
{
Location location = new Location();
location.Show();
}
Location is a custom class which opens a window with 3 list boxes
Thanks, any help is appreciated.
I'm using WPF application on C# 4.0 & Visual Studio 2010.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以在主窗口中创建一个字段,该字段保存对位置窗口的引用(如果有),在按钮单击处理程序中检查该字段是否为空,如果不是,则创建一个新窗口并将其存储在该字段中在字段中的窗口上调用
Activate
。您还必须订阅位置窗口的Closed
事件,以便在位置窗口消失时再次清除引用。编辑:具体示例:
You could create a field in your main window which holds a reference to the location window if there is any, in the button click handler check if the field is null and if it is create a new window and store it in the field, if not call
Activate
on the window in the field. You also would have to subscribe to theClosed
event of the location window to clear out the reference again when the location window is gone.Edit: Concrete example:
Application.Current.Windows 集合保存当前AppDomain 的所有窗口的引用。您可以在该集合中检查您的窗口,如果找到您的窗口,则为该窗口调用激活,否则创建新窗口。这将帮助您继续 -
确保为您的窗口提供一个
x:Name
作为 LocationWindow 以使其正常工作。还要在后面的代码中包含命名空间
System.Linq
。Application.Current.Windows collection holds reference for all windows for current AppDomain. You can check for your window in that collection and if it founds your window then call Activate for that window else create new Window. This will get you going -
Make sure you provide your window a
x:Name
as LocationWindow to make it work.Also include namespace
System.Linq
in your code behind.