Programmatically adding a toolstrip button and attaching click event

1.8k Views Asked by At

I have a class which creates toolstrip buttons for a C1Editor and it works fine because the commands are inbuilt. There are about five forms that uses this class to create their toolstrip buttons. I am adding a custom button and this requires a click event, this is where I am lost. I need your help folks. The class code is below:

public class AlrFrontEndToolStrip : C1EditorToolStripBase
{
    protected override void OnInitialize()
    {
        base.OnInitialize();
        AddButton(CommandButton.Copy);
        AddButton(CommandButton.Paste);
        Items.Add(new ToolStripSeparator());
        AddButton(CommandButton.SelectAll);
        AddButton(CommandButton.Find);
        Items.Add(new ToolStripSeparator());
        AddButton(CommandButton.Print);
        Items.Add(new ToolStripSeparator());
        Items.Add(new ToolStripButton().Text = "View Judgment", Properties.Resources.Find_VS, onClick: EventHandler.CreateDelegate( "Push");
    }
}

If I remove the following bit: 'onClick: EventHandler.CreateDelegate( "Push")', it works perfectly. How then can I make the button clickable in the various forms and each implementing their own click.

1

There are 1 best solutions below

0
On

Here's a WPF-style sample how you can do it with the standard ToolStrip, but the same should work for you as well. This code is creating a new control, that is a ToolStrip with one button added. It exposes BtnClickCommand property giving you an opportunity to provide your handler for the Click event using a Command

[System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.AutoDispatch)]
[System.Runtime.InteropServices.ComVisible(true)]
public class CustomToolstrip : ToolStrip
{
    public CustomToolstrip() : base()
    {
        InitializeComponent();
    }
    public void InitializeComponent()
    {
        var btn = new ToolStripButton()
        {
            Text = "Test Button"
        };

        btn.Click += BtnOnClick;
        Items.Add(btn);

    }

    private void BtnOnClick(object sender, EventArgs eventArgs)
    {
        if (BtnClickCommand.CanExecute(null))
        BtnClickCommand.Execute(null);
    }

    public ICommand BtnClickCommand { get; set; }
}

Then in the form you use it as follows (assuming the control name is customToolstrip1):

    public Form1()
    {
        InitializeComponent();
        customToolstrip1.BtnClickCommand = new RelayCommand<object>(obj => { MessageBox.Show("Button clicked"); });
    }