当您每次单击按钮时都会创建一个新的 JungleTimer 时,您将始终获得一个新的窗口实例。您需要做的是在 JungleTimer 类型的类中声明一个字段。最初这将为空(无)。单击按钮时,检查此字段是否有值或仍为空。如果仍然为空,请将其设置为新的 JungleTimer 并显示它。如果它不为空,则激活现有窗口而不创建新实例。您还需要检测窗口何时关闭,以便将字段设置回 null。
对于演示,创建一个带有两个窗口的新 WPF 应用程序,MainWindow(主窗口)和 JungleTimer。
主窗口的 XAML:
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<StackPanel VerticalAlignment="Center">
<Button Width="100" Height="30" Click="Jungle_Click">Jungle Me</Button>
<Button Width="100" Height="30" Click="DeJungle_Click">De-Jungle Me</Button>
</StackPanel>
MainWindow 的 VB (对不起,如果它很笨拙,我已经十年左右没有做过 VB):
Class MainWindow
Private WithEvents _jungleTimer As JungleTimer
Private Sub Jungle_Click(sender As Object, e As RoutedEventArgs)
If _jungleTimer Is Nothing Then
_jungleTimer = New JungleTimer
_jungleTimer.Show()
Else
_jungleTimer.Activate()
End If
End Sub
Private Sub DeJungle_Click(sender As Object, e As RoutedEventArgs)
If Not _jungleTimer Is Nothing Then
_jungleTimer.Hide()
_jungleTimer = Nothing
End If
End Sub
Private Sub CloseHandler() Handles _jungleTimer.Closed
_jungleTimer = Nothing
End Sub
End Class
丛林窗口的 XAML:
<Window x:Class="JungleTimer"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="JungleTimer" Height="300" Width="300">
<Grid>
<Label HorizontalAlignment="Center" VerticalAlignment="Center">
Jungle!
</Label>
</Grid>