[UWP] Variable Number of MenuFlyoutItems

Md. Niaz Mahmud 171 Reputation points
2021-09-08T16:39:48.537+00:00

Is it possible to implement MenuFlyout with variable number of MenuFlyoutItem/ToggleMenuFlyoutItem in UWP??? If yes, how is it? How to get the individual click event?

Universal Windows Platform (UWP)
0 comments No comments
{count} votes

Accepted answer
  1. Roy Li - MSFT 32,721 Reputation points Microsoft Vendor
    2021-09-09T03:21:36.8+00:00

    Hello,

    Welcome to Microsoft Q&A!

    Based on @Castorix31 's reply, you could check the MenuFlyout Class or take a look at the simplified code here:

    Xaml:

       <Rectangle x:Name="Rect1" Height="100" Width="200"   
                   Stroke="Black" StrokeThickness="1" Fill="White">  
                <Rectangle.ContextFlyout>  
                    <MenuFlyout x:Name="RectangleColorMenu"/>  
                </Rectangle.ContextFlyout>  
            </Rectangle>  
    

    Code-behind

    To add items

     // Create the menu item.  
                var newMenuItem = new MenuFlyoutItem();  
                newMenuItem.Text ="YourItemName";  
                newMenuItem.Click += (s, e1) =>  
                {  
                    Rect1.Fill = new SolidColorBrush(Colors.Red);  
                };  
      
                // Add the item to the menu.  
                RectangleColorMenu.Items.Add(newMenuItem);  
      
                // Sort the menu so it's always consistent.  
                var orderedItems = RectangleColorMenu.Items.OrderBy(i => ((MenuFlyoutItem)i).Text).ToList();  
                RectangleColorMenu.Items.Clear();  
                foreach (var item in orderedItems)  
                {  
                    RectangleColorMenu.Items.Add(item);  
                }  
    

    To remove items:

     // Get any menu items to remove and remove them.  
                var items = RectangleColorMenu.Items.Where(i => ((MenuFlyoutItem)i).Text == "YourItemName");  
                foreach (MenuFlyoutItem item in items)  
                {  
                    RectangleColorMenu.Items.Remove(item);  
                }  
    

    Thank you.


    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Castorix31 82,316 Reputation points
    2021-09-08T18:15:29.057+00:00

    In the doc, there is a sample at MenuFlyout Class:

    (part : This example shows how you can add and remove menu items at runtime based on changing conditions in your app.)

    0 comments No comments