【问题标题】:How to close Popup with trigger button如何使用触发按钮关闭弹出窗口
【发布时间】:2017-08-29 20:48:22
【问题描述】:

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

这是我的 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;
}

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

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

【问题讨论】:

标签: c# wpf xaml popup


【解决方案1】:

@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;
        }
    }

希望这可以帮助其他可能遇到此问题的人。最重要的是,您通常应该使用切换按钮来打开和关闭弹出窗口。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-06
    • 1970-01-01
    相关资源
    最近更新 更多