Is there a way to assign shortcut keys to the standard navigation ToolStrip Items in a BindingNavigator?

The items that get added using the .AddStandardItems method are of type ToolStripItem which doesn't have a ShortcutKeys property.

I tried to cast to ToolStripMenuItem , but it fails.

 public void ConfigureMyNavigator()
    {
               // Adds ToolStripItems which don't support shortcut keys           
                m_navigator.AddStandardItems();

                // Adds a ToolStripMenuItem which can support a shortcut key
                var button = new ToolStripMenuItem
                {
                    Size = new Size(0, 0),
                    Text = "Save",
                    ShortcutKeys = (Keys)Shortcut.CtrlS,
                    ToolTipText = "Press Ctrl+S to save"
                };
                button.Click += tsmi_Click;

                m_navigator.Items.Add(button);

                //   This fails with invalid cast exception
                ((ToolStripMenuItem)m_navigator.Items[1]).ShortcutKeys = (Keys)Shortcut.AltLeftArrow;


    }

I guess I could replace the toolstripitems with toolstripmenuitems one by one, but feel this is rather awkward.

有帮助吗?

解决方案

You can listen for key commands and then raise the click of the appropriate ToolStripButton. Override the ProcessCmdKey method in your form code:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    switch (keyData)
    {
        case (Keys.Alt | Keys.Left):
            m_navigator.Items[1].PerformClick();
            break;
        case (Keys.Alt | Keys.Right):
            m_navigator.Items[6].PerformClick();
            break;
    }

    return base.ProcessCmdKey(ref msg, keyData);
}

其他提示

Did you try adding "&" symbol in front of the button caption?

Text = "&Save"

You can override the AddStandardItems method and overload the ToolStripMenuItem's constructor to accept ToolStripItem as a parameter for easier creation of the items.

But it's still sort of "replacing the items one by one".

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top