Sam
Sam

Reputation: 349

How to close the pop up window when I click outside of popup window

Here is XAML code for open popup window IsChecked btnViewDetail, I need to close popup on click out side of popup window.

<Popup IsOpen="{Binding IsChecked, ElementName=btnViewDetail}" PopupAnimation="Fade" Width="300" Height="225" PlacementTarget="{Binding ElementName=svTotalStock}" Placement="Top" StaysOpen="False">
    <Grid Background="Black">
        <TextBlock TextWrapping="Wrap" Text="Raw Materials details" 
                   VerticalAlignment="Top" Height="25" FontFamily="Segoe UI Semibold" 
                   Padding="7,6,0,0" FontWeight="Bold" FontSize="14" Foreground="White" 
                   Margin="0,2,59,0"/>
        <Border BorderThickness="1" BorderBrush="Black"/>
    </Grid>
</Popup>
<Grid>
    <Grid.ContextMenu>
        <ContextMenu>
            <MenuItem IsCheckable="True" Name="btnViewDetail" Header="View Details"/>
        </ContextMenu>
    </Grid.ContextMenu>
</Grid>

Upvotes: 17

Views: 19291

Answers (5)

Mahadev Swamy
Mahadev Swamy

Reputation: 131

add a togglebutton and bind IsOpen property of popup to IsChecked property of ToggleButton as shown below:

    <ToggleButton IsChecked = {Binding ElementName = "Your_Popup_Name", Path = "IsOpen", Mode = "TwoWay"} Opacity = "0" , Panel.ZIndex = "1">

Upvotes: 0

sahithi
sahithi

Reputation: 1089

I suspect the control from where the popup is opened. I even had same issue and reloved by opening the popup by MouseLeftButtonUp of the target.

Upvotes: 1

Danil Shaykhutdinov
Danil Shaykhutdinov

Reputation: 2277

property of Popup StaysOpen = false do this work.

Upvotes: 30

itzmebibin
itzmebibin

Reputation: 9439

There are two properties you have to assign:

StaysOpen = false ,

When the StaysOpen property is set to true, Popup stays open until it is explicitly closed by setting the IsOpen property to false. When StaysOpen is false, the Popup control intercepts all mouse and keyboard events to determine when one of these events occurs outside the Popup control.

Next, set popup's child : Focusable = false

Then in other User Control which u wants tp open the popup, define an EventTrigger on UIElement.LostMouseCapture to set the popup's IsOpen = true;

Upvotes: 4

Javad Ebrahimi
Javad Ebrahimi

Reputation: 359

if StaysOpen property cannot handle your situation, you have to capture MouseDown event on your Window when your container element(in your situation, Grid) has Focusable="True"

private void Window_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
    gridContainer.Focus();
}

Upvotes: 6

Related Questions