In my UWP application, I need a Popup. And by setting its IsLightDismissEnabled="True"
, I can hide the popup when clicking outside of it.
But I notice that, when doing so, if a button is there, then clicking the button will only cause the popup hidden while the button is not really pressed.
What I want is when popup is shown, and clicking the outside of the popup, e.g. the "Button 2" as below picture shown, will hide the popup and invoke the button clicking event simultaneously.
Below is my code: https://github.com/tomxue/PopupDemo.git
<Grid>
<Button Width="100" Height="50" Click="Button_Click" Content="Button 1"></Button>
<Popup x:Name="popup" IsLightDismissEnabled="True">
<Grid Width="200" Height="200" Background="AliceBlue"></Grid>
</Popup>
<Button Width="100" Height="50" Margin="300 0 0 0" Content="Button 2" Click="Button2_Click"></Button>
</Grid>
The screenshot is as below. When clicking Button 2 in picture-1, we will come to picture-2. And if clicking Button 2 in picture-2 again, then a message dialog is shown in picture-3.
My expectation: when clicking Button 2 in picture-1, just hide popup and show message dialog like picture-3 shown.
When button 1 is pressed, the popup appears, and the entire process is waiting for the user to close the popup, and no other operations can be performed. Therefore, we cannot directly reach the third step.
If you want to go directly from the first step to the third step, it is recommended that you abandon popup and use Visibility to achieve a similar popup effect.
In the following example, I use a transparent Rectangle to obtain the click event in the Grid to obtain the same effect as IsLightDismissEnabled="True
.
<Grid>
<Rectangle HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Fill="Transparent"
Tapped="Rectangle_Tapped"/>
<Button Width="100" Height="50" Click="Button_Click" Content="Button 1"></Button>
<Grid x:Name="grid" VerticalAlignment="Top" HorizontalAlignment="Left" Width="200" Height="200" Background="Yellow" Visibility="Collapsed"></Grid>
<Button Width="100" Height="50" Margin="300 0 0 0" Content="Button 2" Click="Button2_Click"></Button>
</Grid>
private void Button_Click(object sender, RoutedEventArgs e)
{
//popup.IsOpen = !(popup.IsOpen);
if (grid.Visibility==Visibility.Visible)
{
grid.Visibility = Visibility.Collapsed;
}
else
{
grid.Visibility = Visibility.Visible;
}
}
private async void Button2_Click(object sender, RoutedEventArgs e)
{
grid.Visibility = Visibility.Collapsed;
var messageDialog = new MessageDialog("Hello");
await messageDialog.ShowAsync();
}
private void Rectangle_Tapped(object sender, Windows.UI.Xaml.Input.TappedRoutedEventArgs e)
{
grid.Visibility = Visibility.Collapsed;
}