tags:

views:

549

answers:

2

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.

A: 

I would try a more WPF-esque approach. Instead of doing code behind, I would try to bind properties. If you change the Button for a ToggleButton it's easy. You see, ToggleButton has a Boolean property named 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>

What do you think?

Tio Luiso
A: 

Tio. This is the solution I'm trying too. However there are two problems with it.

1) When you press the button, the popup opens, however if you press the button again, the popup closes, and then rapidly opens again. That is not the behavior I expected, I thought it would close again then.

2) If you tab away from the toggle button, the popup stays open.

I googled around a bit, of course some other guy had had the same problem, and solved it :=)

check this out: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/f0502813-9c4f-4b45-bab8-91f98971e407

Magnus Gud