0

wpf テンプレートを使用してアプリケーションを開発しています。MainWindow.xaml と Windows フォームである JungleTimer.vb の 2 つのウィンドウがあります。

メイン ウィンドウに、次のコードを使用して JungleTimer フォームを表示するボタンがあります。

Dim JungleTimer As New JungleTimer
        JungleTimer.Show()

しかし、ご覧のとおり、このボタンを複数回クリックすると、複数の JungleTime フォームが表示されます。このコードを使用して、JungleTimer が表示されているかどうかを確認しようとしましたが、機能しません。

Dim JungleTimer As New JungleTimer
        If JungleTimer.Visible = False Then
            JungleTimer.Show()
        End If

JungleTimer フォームを閉じるコードも必要です。

4

1 に答える 1

2

ボタンをクリックするたびに新しい JungleTimer を作成しているため、常にウィンドウの新しいインスタンスが取得されます。必要なのは、JungleTimer 型のクラス内でフィールドを宣言することです。最初は null (Nothing) になります。ボタンをクリックすると、このフィールドに値があるかどうか、またはまだ null であるかどうかを確認します。それでも null の場合は、新しい JungleTimer に設定して表示します。null でない場合は、新しいインスタンスを作成せずに既存のウィンドウをアクティブにします。また、フィールドを null に戻すことができるように、ウィンドウが閉じるタイミングを検出する必要があります。

デモ用に、MainWindow (メイン ウィンドウ) と JungleTimer の 2 つのウィンドウを持つ新しい WPF アプリケーションを作成します。

MainWindow の 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 (不器用な場合は申し訳ありませんが、私は 10 年ほど 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

JungleWindow の 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>

于 2013-06-09T17:04:47.227 に答える