.netmauimarkup-extensionsmaui-community-toolkit

.MAUI: How to add context menu into control by using community-toolkit-markup or C#


Now in .Net7 I can add context menu into control like this:

Entry
                    x:Name="MyEntry"
                
                    BackgroundColor="AliceBlue"
                    
                    Keyboard="{Binding KeyboardValue, Source={x:Reference Me}}"
                    TextColor="{Binding TextColor, Source={x:Reference Me}}"
                
                    VerticalTextAlignment="Center" 
                    HorizontalOptions ="Fill"
                    HorizontalTextAlignment="{Binding HorizontalTextAlignmentOption, Source={x:Reference Me}}"
            
                    IsEnabled="{Binding IsEnable, Source={x:Reference Me}}"
                    IsReadOnly="{Binding IsReadOnly, Source={x:Reference Me}}"
            
                    Text="{Binding TextValue, Source={x:Reference Me}}"
            
                    Placeholder="{Binding Placeholder, Source={x:Reference Me}}"
                    ToolTipProperties.Text="{Binding TooltipValue, Source={x:Reference Me}}"
                >

                    <FlyoutBase.ContextFlyout>
                        <MenuFlyout x:Name="MyContextMenus">
                            <MenuFlyoutItem Text="Menu1"/>
                            <MenuFlyoutItem Text="Menu2"/>
                        </MenuFlyout>
                    </FlyoutBase.ContextFlyout>
                </Entry>

But we need using C# Markup for using conditional (in some case) to display context menu of the control - instead of use XAML like above. How can we do it?


Solution

  • You can try to add it with the C# code such as:

    MenuFlyout menuElements = new MenuFlyout();
    MenuFlyoutItem item1 = new MenuFlyoutItem() { Text = "menu1" };
    MenuFlyoutItem item2 = new MenuFlyoutItem() { Text = "menu2" };
    menuElements.Add(item1);
    menuElements.Add(item2);
    FlyoutBase.SetContextFlyout(MyEntry, menuElements);