Search code examples
c#winformsdevexpresspopupmenutreelist

Context menu shows changes on next click


I am using a DevExpress TreeList. I have two methods MouseDown() and MouseUP() to get the item from the treelist by right click and then show a contextmenu/popup menu with changes to it at runtime.

Problem: ContextMenu or PopupMenu displays the barSubItem3.Enabled = false;change on the next click. Not on the current click.

private void TreeList1_MouseDown(object sender, MouseEventArgs e)
    {
        TreeList tree = sender as TreeList;
        if (e.Button == MouseButtons.Right && ModifierKeys == Keys.None
            && tree.State == TreeListState.Regular)
        {
            Point pt = tree.PointToClient(MousePosition);
            TreeListHitInfo info = tree.CalcHitInfo(pt);

            if (info.HitInfoType == HitInfoType.Cell)
            {
                SavedFocused = new TreeListNode();
                SavedFocused = tree.FocusedNode;
                tree.FocusedNode = info.Node;

            /* get value from node that is clicked by column index */
                switch (SavedFocused.GetValue(0).ToString())
                {
                    case "A":
                        barSubItem3.Enabled = false;
                        break;
                    case "B":
                        barSubItem3.Enabled = true;
                        break;
                }

            }

        }
    }

private void TreeList1_MouseUp1(object sender, MouseEventArgs e)
    {

        TreeList tree = sender as TreeList;
        if (e.Button == MouseButtons.Right && ModifierKeys == Keys.None
            && tree.State == TreeListState.Regular)
        {

            popUpMenu.ShowPopup(MousePosition);
        }
    }  

Solution

  • I guess that's happening because you're actually modifying the state of the item once it's already being shown.

    Use the PopupMenuShowing event instead. Here is an example on how to modify the PopUpMenu using a GridView.

    private void Whatever_PopupMenuShowing(object sender, DevExpress.XtraGrid.Views.Grid.PopupMenuShowingEventArgs e)
    {
        var menu = e.Menu;
        var hi = e.HitInfo;
        if (!(sender is GridView view)) 
            return;
    
        var inDetails = (hi.HitTest == GridHitTest.EmptyRow);
        if (menu == null && inDetails)
        {
            menu = new DevExpress.XtraGrid.Menu.GridViewMenu(view);
            e.Menu = menu;
        }
        if (menu == null) 
            return;
    
        //If there are any entries, show "Duplicate" button
        var rowHandle = hi.RowHandle;
        if (!view.IsDataRow(rowHandle)) return;
        var mnuDuplicate = new DXMenuItem("Duplicate",
            async delegate { await ClickDuplicate(); },
            Properties.Resources.copy_16x16)
        {
            BeginGroup = true
        };
        menu.Items.Add(mnuDuplicate);
    }