在 WPF 中使用 Popup.StaysOpen 在鼠标单击时隐藏弹出窗口

Tol*_*Ch. 4 wpf popup

我得到了包含以下内容的用户控件:

  • 按钮
  • 弹出窗口(包含文本块)

XAML

<UserControl>
<button Name="btnShowPopup" Content="Button" Click="Button_Click"/>
<Popup Name="popup" StaysOpen="true">
<TextBlock Text="Popup"/>
</Popup>
</UserControl>
Run Code Online (Sandbox Code Playgroud)

代码隐藏

private void Button_Click(object sender, System.Windows.RoutedEventArgs e)
{
   this.popup.IsOpen=!this.popup.IsOpen;
}
Run Code Online (Sandbox Code Playgroud)

问题:当鼠标单击 btnShowPopup 按钮外的任何地方时,我想隐藏弹出窗口。

注意:我尝试过更改StaysOpen="false"和当btnShowPopup.MouseDown事件: this.popup.IsOpen=!this.popup.IsOpen; 但是这个解决方案会导致另一个问题:当btnShowPopup.MouseUp事件发生时,弹出窗口消失。

请帮忙。

小智 5

您还可以在切换按钮上绑定 StaysOpen 属性:

StaysOpen="{Binding ElementName=toggleButton,Path=IsMouseOver}"
Run Code Online (Sandbox Code Playgroud)

https://social.msdn.microsoft.com/Forums/vstudio/en-US/f0502813-9c4f-4b45-bab8-91f98971e407/popup-popupstaysopen-togglebutton-and-data-binding-helpful-tip?forum=wpf

我的问题是,如果我双击我的数据网格,它在弹出窗口中,弹出窗口会直接重新打开,这就是我使用多重绑定的原因。我做了什么:

我多绑定了 IsMouseOver toggleButton 上的 StayOpen 属性和弹出窗口中的 IsMouseOver 数据网格。

<Popup.StaysOpen>
    <MultiBinding Converter="{StaticResource MultiBinding_StayOpen}">
        <Binding ElementName="toggleButton"  Path="IsMouseOver"/>
        <Binding ElementName="dtg_loc" Path="IsMouseOver" />
    </MultiBinding>
</Popup.StaysOpen>
Run Code Online (Sandbox Code Playgroud)

multiBindingConverter :

public class MultiBinding_StayOpen : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {

        bool toggleIsMouseOver;
        bool datagridIsMouseOver;

        toggleIsMouseOver = System.Convert.ToBoolean(values[0]);
        datagridIsMouseOver = System.Convert.ToBoolean(values[1]);


        if (toggleIsMouseOver == false && datagridIsMouseOver == false)
            return false;

        if (toggleIsMouseOver == true && datagridIsMouseOver == false)
            return true;

        if (toggleIsMouseOver == true && datagridIsMouseOver == true)
            return false;

        return true;
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
Run Code Online (Sandbox Code Playgroud)

希望它有帮助:-)


小智 3

我会尝试一种更像 WPF 的方法。我会尝试绑定属性,而不是在后面执行代码。如果将 Button 更改为 ToggleButton,则很容易。你看,ToggleButton 有一个名为 IsChecked 的布尔属性

<ToggleButton x:Name="myToggle" />
<Popup x:Name="Popup"
    IsOpen="{Binding Path=IsChecked, ElementName=myToggle}"
    Placement="Right"
    PlacementTarget="{Binding ElementName=myToggle}"
    AllowsTransparency="True" 
    Focusable="False"
    PopupAnimation="Fade"
    StaysOpen="False">
    <Textblock Text="Here goes my content" />
</Popup>
Run Code Online (Sandbox Code Playgroud)

你怎么认为?