Home > Net >  Why is MenuFlyout.Items always null in Closing event?
Why is MenuFlyout.Items always null in Closing event?

Time:11-04

I can successfully add a MenuFlyoutItem to a MenuFlyout dynamically in the ContextMenuFlyout_Opening event, but when I try to remove it in ContextMenuFlyout_Closing the MenuFlyout.Items is always null and the MFI isnt found and removed.

Any ideas why this is so?

<Page.Resources>
    <MenuFlyout
    x:Key="ListViewContextMenu"
    Closing="{x:Bind ViewModel.ContextMenuFlyout_Closing}"
    Opening="{x:Bind ViewModel.ContextMenuFlyout_Opening}">

    <MenuFlyoutItem
        Click="{x:Bind ViewModel.EditParty}"
        Icon="Edit"
        Text="Edit" />

    <MenuFlyoutItem Text="Open in new window">
        <MenuFlyoutItem.Icon>
            <FontIcon
                FontFamily="Segoe MDL2 Assets"
                FontSize="40"
                Glyph="&#xE8A7;" />
        </MenuFlyoutItem.Icon>
    </MenuFlyoutItem>

    <MenuFlyoutSeparator />

    <MenuFlyoutItem
        Click="MenuFlyoutItem_Click"
        Icon="Delete"
        Text="Delete" />

    </MenuFlyout>
</Page.Resources>

ViewModel event handlers

public void ContextMenuFlyout_Opening(object sender, object e)
{
    MenuFlyout flyout = sender as MenuFlyout;
    if (flyout != null)
    {
        // If party.IsConflict = true then add the MFI
        if (SelectedTalent.IsConflict)
        {
            flyout.Items.Add(new MenuFlyoutItem()
            {
                Icon = new FontIcon() { Glyph = "\uEC4F" },
                Text = "Resolve Conflict"
            });
        }
    }           
}

public void ContextMenuFlyout_Closing(object sender, object e)
{
    // Remove 'Resolve Conflict' MFI if its found

    MenuFlyout flyout = sender as MenuFlyout;
    if (flyout != null)
    {
        var rc = flyout.Items.FirstOrDefault(o => o.Name == "Resolve Conflict");
        if (rc != null)
        {
            flyout.Items.Remove(rc);
        }
    }
}

ListView that uses the MenuFlyout

    <ListView
    ContextFlyout="{StaticResource ListViewContextMenu}"

CodePudding user response:

Based on your code, it seems that you are trying to get the MenuFlyoutItem object by name. But you forget to give the MenuFlyoutItem object a Name when you add it to the MenuFlyout, you just added a Text property.

  flyout.Items.Add(new MenuFlyoutItem()
                {
                    Icon = new FontIcon() { Glyph = "\uEC4F" },
                    Text = "Resolve Conflict",
                    Name = "Resolve Conflict",
                });
  • Related