0

I have a custom control AsGridItem which is a customized button that am creating pragmatically and adding to a WrapPanel. I need help to implement the context menu fully on it so that I can delete the referenced item from my db or even open a new window or show a popup window.

private void LoadItems(List<MyItems> items)
    {
        foreach (item in items)
        {
            AsGridItem asGrid = new AsGridItem();
            asGrid.Title = item.Title;
            asGrid.Icon = item.IconName;
            asGrid.PackIcon = item.ContentType;

            MenuItem editMenu1 = new MenuItem();
            editMenu1.Header = "Open this Item";
            editMenu1.Click += ItemOpen_Click;

            MenuItem editMenu2 = new MenuItem();
            editMenu2.Header = "Delete this Item";
            editMenu2.Click += ItemDelete_Click;

            MenuItem editMenu3 = new MenuItem();
            editMenu3.Header = "View Properties";
            editMenu3.Click += ItemProperties_Click;

            ContextMenu contextMenu = new ContextMenu();
            contextMenu.Items.Add(editMenu1);
            contextMenu.Items.Add(editMenu2);
            contextMenu.Items.Add(editMenu3);

            asGrid.ContextMenu = contextMenu;
            asGrid.Click += GridItem_Click;

            ItemsList.Children.Add(asGrid);
        }
    }

    private void GridItem_Click(object sender, RoutedEventArgs e)
    {
        AsGridItem asGrid = sender as AsGridItem;
        OpenItem(asGrid);
    }

    private void ItemOpen_Click(object sender, RoutedEventArgs e)
    {
        AsGridItem asGrid = sender as AsGridItem;
        OpenItem(asGrid);
    }

I am the error of object set to a null reference and I cant figure how to solve this.

  • 1
    Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Sinatr Jul 17 '19 at 07:35
  • yeah but looks like the item that am parsing from sender is not well traced and I don't know how to reference it based on what I have here at the moment –  Jul 17 '19 at 07:37

1 Answers1

0

You are getting a null reference because you are using the code that is meant for onclick of the item when you should be reference the menuitem clicked on what contextmenu of what item in your wrappanel.

MENUITEM >> CONTEXTMENU >> ITEM

I just modified the code a bit to implement this

private void ItemOpen_Click(object sender, RoutedEventArgs e)
{
    //try to reference the menuItem first
    MenuItem menuItem = (MenuItem)sender;

    //then reference the contextmenu
    ContextMenu contextMenu = (ContextMenu)menuItem.Parent;

    // then your initial code can come in modfied like this
    AsGridItem asGrid = (AsGridItem)contextMenu.PlacementTarget;
    OpenItem(asGrid);
}

I hope it will solve your issue of the null reference error