Partager via


Return a value from Windows 10 UWP MenuFlyout control

Using the Windows 10 UWP MenuFlyout control, but don't see how to return a value from the selected options? You could sub-class MenuFlyoutItem, but don't overthink it: just use the .Tag property in MenuFlyoutItem, like this:

 

private void button_Click(object sender, RoutedEventArgs e)
{
// Open a MenuFlyout

var myMenuFlyout = new MenuFlyout();

// Create the menu options
var option1 = new MenuFlyoutItem() { Text = "Return a value of 1" };
var option2 = new MenuFlyoutItem() { Text = "Return a value of 2" };
var option3 = new MenuFlyoutItem() { Text = "Returna  value of 3" };

// Add the handler called when the user select the menu option
option1.Click += MenuFlyoutHandler_Click;
option2.Click += MenuFlyoutHandler_Click;
option3.Click += MenuFlyoutHandler_Click;

// Define the value you want the menu options to return
option1.Tag = 1;
option2.Tag = 2;
option3.Tag = 3;

// Add the options to the menu control
myMenuFlyout.Items.Add(option1);
myMenuFlyout.Items.Add(option2);
myMenuFlyout.Items.Add(option3);

// Display the menu, with an on-screen position relative to another control -
// usually the control that caused it to appear.
myMenuFlyout.ShowAt(button);

}

private void MenuFlyoutHandler_Click(object sender, RoutedEventArgs e)
{
var returnValue = ((MenuFlyoutItem)sender).Tag;
}
}