Trying to pass a parameter to a new EventHandler

Viewed 541

I am using the new WebView2 to insert text into a textbox within Edge. I have the event below:

webView.NavigationCompleted += new EventHandler<CoreWebView2NavigationCompletedEventArgs>(InputText);

It runs the following code:

private async void InputText(object sender, CoreWebView2NavigationCompletedEventArgs args)
{
    await webView.ExecuteScriptAsync("document.getElementById('Textbox').value = 'Test';");
}

This works for the test site I am playing with. However, I want to pass the script as a string variable into the InputText method. Trying to add it to it states, that there is no overload for the delegate such as:

webView.NavigationCompleted += new EventHandler<CoreWebView2NavigationCompletedEventArgs>(e => InputText(this, e, "Test"));

private async void InputText(object sender, CoreWebView2NavigationCompletedEventArgs args, string test)
{
    await webView.ExecuteScriptAsync("document.getElementById('Textbox').value = 'Test';");
}

Is there a way to overload this to add a parameter?

1 Answers

The EventHandler<CoreWebView2NavigationCompletedEventArgs> delegate has signature that delares a parameter sender of type object and e of type CoreWebView2NavigationCompletedEventArgs.

public delegate void EventHandler<CoreWebView2NavigationCompletedEventArgs>(object sender, CoreWebView2NavigationCompletedEventArgs e);

However, the lambda expression e => InputText(this, e, "Test") has only one parameter e. You need to add a second parameter for sender to match the delegate signature above. Let's call it s.

(s, e) => InputText(this, e, "Test")

If you do not use the parameter anyway, you can also ignore it explicitly with the discard operator.

(_, e) => InputText(this, e, "Test")

Please also make sure that your test parameter is used in your method. Here I use string interpolation with $ to insert the value of test into your script.

private async void InputText(object sender, CoreWebView2NavigationCompletedEventArgs args, string test)
{
    await webView.ExecuteScriptAsync($"document.getElementById('Textbox').value = '{test}';");
}
Related