1

Is it possible to close/hide programmatically a PopupMenu in WinRT?

I tried to set focus on something else, but it doesn't work. This class (PopupMenu) doesn't provide methods to close it either.

I also tried to replace PopupMenu with MenuFlyout, but in my case when another view shows up, items are gone and it is not possible to hide it anymore (programmatically).

Screenshot:

MenuFlyout

Wojciech Kulik
  • 7,823
  • 6
  • 41
  • 67

2 Answers2

0

There is no way to programmatically hide the Menu once its shown.

You show it with a ShowAsync(position) call which you await. The only way for that await call to relinquish control is to either select an option from the menu (you could a cancel option) or click anywhere off of the Menu.

What are you using it for and why would you need to cancel it once its shown rather than have the user cancel it themselves? I can imagine at least one scenario where I'd want it to disappear like if a user opened the popup menu and then a background process finished and the commands on the popup menu are no longer applicable or they need to be updated. But what is your usage scenario -- perhaps there is a workaround for your situation?

CarCar
  • 680
  • 4
  • 13
0

I have found a solution for my problem, but I had to replace PopupMenu with FlyoutMenu. Instead of using Commands from PopupMenu I just attached click event handlers to items.

public static class FlyoutHelper
{
    public static readonly DependencyProperty IsHiddenProperty =
        DependencyProperty.RegisterAttached("IsHidden", typeof(bool), typeof(FlyoutHelper), new PropertyMetadata(false, OnIsHiddenPropertyChanged));

    public static void SetIsHidden(DependencyObject d, bool value)
    {
        d.SetValue(IsHiddenProperty, value);
    }

    public static bool GetIsHidden(DependencyObject d)
    {
        return (bool)d.GetValue(IsHiddenProperty);
    }

    private static void OnIsHiddenPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var flyout = d as FlyoutBase;
        bool isHidden = (bool)e.NewValue;

        if (flyout != null && isHidden)
        {
            flyout.Hide();
        }
    }
}

Usage:

<MenuFlyout helpers:FlyoutHelper.IsHidden="{Binding IsFlyoutHidden}">
    <MenuFlyoutItem Click="Item1Clicked" />
    <MenuFlyoutItem Click="Item2Clicked" />
</MenuFlyout>

To hide a flyout you only need to switch IsFlyoutHidden in view model to true.

Wojciech Kulik
  • 7,823
  • 6
  • 41
  • 67