Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hiding popup on mouse click with Popup.StaysOpen in WPF

Tags:

wpf

popup

I got my UserControl that contain:

  • Button
  • Popup (contain Text block)

XAML

<UserControl>
<button Name="btnShowPopup" Content="Button" Click="Button_Click"/>
<Popup Name="popup" StaysOpen="true">
<TextBlock Text="Popup"/>
</Popup>
</UserControl>

Code Behide

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

QUESTION: I want to hide the popup, when mouse click on anywhere outside the btnShowPopup button.

NOTE: I tried change StaysOpen="false" and when btnShowPopup.MouseDown event: this.popup.IsOpen=!this.popup.IsOpen; But this solution cause another problem: when btnShowPopup.MouseUp event, the Popup is disappear.

Please help.

like image 672
Tola Ch. Avatar asked Feb 22 '10 01:02

Tola Ch.


2 Answers

You can also bind the StaysOpen property on the togglebutton :

StaysOpen="{Binding ElementName=toggleButton,Path=IsMouseOver}"

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

The problem for me was if i double clicked on my datagrid, wich is in the popup, the popup re opened directly, that's why i used the multibinding. What i've done :

I Multi binded the StayOpen property on IsMouseOver toggleButton and on my IsMouseOver datagrid wich is in the popup.

<Popup.StaysOpen>
    <MultiBinding Converter="{StaticResource MultiBinding_StayOpen}">
        <Binding ElementName="toggleButton"  Path="IsMouseOver"/>
        <Binding ElementName="dtg_loc" Path="IsMouseOver" />
    </MultiBinding>
</Popup.StaysOpen>

The 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();
    }
}

Hope it help :-)

like image 91
draco951 Avatar answered Oct 14 '22 20:10

draco951


Set The Property ClickMode="Press" on the Toggle Button.

<ToggleButton x:Name="myToggle" ClickMode="Press" />
like image 31
flusser Avatar answered Oct 14 '22 20:10

flusser