开发者

Passing a Method to a class for EventHandlers

开发者 https://www.devze.com 2023-02-18 23:42 出处:网络
Using a separate class which is being made reusable, need to pass it a function which would be called on the click event from the context menu...

Using a separate class which is being made reusable, need to pass it a function which would be called on the click event from the context menu...

Problem : Functions aren't type EventHandlers.... also Different EventHandlers require different paramters inside... e.g. the OnClose for the exit button....

Edit:

In the Class X

public void AddMenuItem(Strin开发者_StackOverflow中文版g name, EventHandler target )
    {
        MenuItem newItem = new MenuItem();
        newItem.Index = _menuItemIndex++;
        newItem.Text = name;
        newItem.Click += target;

        _contextMenu.MenuItems.Add(newItem);
    }

In the Wpf:

addToTray.AddMenuItem("&Exit", Exit); 

I would love it to link to the following method but at this point any method would do fine.

private void ShouldIExit(object sender, System.ComponentModel.CancelEventArgs e)
    {
        // checks if the Job is running and if so prompts to continue
        if (_screenCaptureSession.Running())
        {
            MessageBoxResult result = System.Windows.MessageBox.Show("Capturing in Progress. Are You Sure You Want To Quit?", "Capturing", MessageBoxButton.YesNo);
            if (result == MessageBoxResult.No)
            {
                e.Cancel = true;
                return;
            }
        }
        _screenCaptureSession.Stop();
        _screenCaptureSession.Dispose();
    }


I'm guessing that the problem is that your ShouldIExit method does not match the EventHandler delegate. Try changing it to take a regular EventArgs parameter, and see if that works. It's best to avoid reusing the same event handler for different event types. You should encapsulate common code into separate methods, and then have different handlers call that code.

private bool CheckExit()
{
    // checks if the Job is running and if so prompts to continue
    if (_screenCaptureSession.Running())
    {
        MessageBoxResult result = System.Windows.MessageBox.Show("Capturing in Progress. Are You Sure You Want To Quit?", "Capturing", MessageBoxButton.YesNo);
        if (result == MessageBoxResult.No)
        {
            return false;
        }
    }
    _screenCaptureSession.Stop();
    _screenCaptureSession.Dispose();
    return true;
}

private void ExitButtonClicked(object sender, System.ComponentModel.CancelEventArgs e)
{
    if (!CheckExit())
    {
        e.Cancel = true;
    }
}

private void ExitMenuItemClicked(object sender, EventArgs e)
{
    CheckExit();
}


It is a bit vauge, but you could probably do

 OnClose += (sender,e) => YourFunction(...)

which has the downside that it not possible to remove the eventhandler again if needed

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号