如何使用触发按钮关闭弹出窗口

时间:2017-08-29 20:48:22

标签: c# wpf xaml popup

您好我需要触发按钮才能打开并关闭弹出窗口,只要在弹出窗口外发生鼠标点击,弹出窗口就会关闭。

这是我的XAML:

<Button x:Name="About"
                    Height="50"
                    Margin="0,-30,5,0"
                    HorizontalAlignment="Right"
                    Style="{StaticResource AboutButtonStyle}" />
<Popup HorizontalOffset="-300"
                   IsOpen="{Binding IsAboutPopupOpen, Mode=TwoWay}"
                   Placement="RelativePoint"
                   PlacementTarget="{Binding ElementName=About}"
                   StaysOpen="False"
                   VerticalOffset="-125">
    <Border Padding="10"
                        Background="White"
                        BorderBrush="{StaticResource SeparatorColorBrush}"
                        BorderThickness="1">
        <TextBlock>Some Text</TextBlock>
    </Border>
</Popup>

在我的AboutViewModel中,我实现了一个属性IsAboutPopupOpen

private bool isAboutPopupOpen;

public bool IsAboutPopupOpen
{
    get
    {
        return this.isAboutPopupOpen;
    }

    set
    {
        if (value != this.isAboutPopupOpen)
        {
            this.isAboutPopupOpen = value;
            this.NotifyOfPropertyChange(() => IsAboutPopupOpen);
        }
    }
}

public void About()
{
    IsAboutPopupOpen = true;
}

问题是,当弹出窗口打开时,我单击“关于”按钮,PopUp将关闭并再次打开。它应该关闭。除此之外,行为是正确的。

我已经找到了一个简单的解决方案,似乎无法找到它。这应该是一个常见的问题。哦,我正在使用Caliburn.Micro,但这不重要,我不会想。感谢

1 个答案:

答案 0 :(得分:0)

@ Xiaoy312指出了我正确的方向。首先我决定使用ToggleButton:

    <ToggleButton
        x:Name="ShowAboutPopup"
        Grid.Row="1"
        Height="50"
        Margin="0,-30,5,0"
        HorizontalAlignment="Right"
        Grid.ZIndex="1000"
        Style="{StaticResource AboutButtonStyle}" />

然后我决定通过IsOpen属性将我的ToggleButton连接到弹出窗口,并将StaysOpen设置为false:

    <Popup
        Grid.Row="1"
        Closed="AboutPopup_OnClosed"
        HorizontalOffset="-300"
        IsOpen="{Binding ElementName=ShowAboutPopup, Path=IsChecked, Mode=OneWay}"
        Placement="RelativePoint"
        PlacementTarget="{Binding ElementName=ShowAboutPopup}"
        StaysOpen="False"
        VerticalOffset="-125">
...
    </Popup>

最后我在代码隐藏中实现了AboutPopup_OnClosed:

    private void AboutPopup_OnClosed(object sender, EventArgs e)
    {
        if (!object.Equals(this.ShowAboutPopup, Mouse.DirectlyOver))
        {
            this.ShowAboutPopup.IsChecked = false;
        }
    }

希望这有助于其他可能与此斗争的人。最重要的是,您通常应该使用切换按钮来打开和关闭弹出窗口。