0

I'm building out a simple ToDoList app using C# and WPF. The goal is that when the button is clicked. The text in a TextBox will be added as a new element in a List which is an existing object instance.

To do this I've updated the Button click event handler's signature to include a parameter to pass the List object. When I compile this code I get an error thrown from my XAML file at the line which contains the Click="AddTaskButton_Click"

Error: No overload for 'AddTaskButton_Click' matches delegate 'RoutedEventHandler'

What could be throwing this error? I've seen other code samples where this compiles fine. Is there another way to accomplish passing "data" or an object to an event handler in WPF? I'm new to WPF.

XAML

<Button
x:Name="AddTaskButton"  Content="+ Add"  
Click="AddTaskButton_Click">
</Button>

Backend C#

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        List<string> taskList = new Tasklist {"Task A", "Task B", "Task C"}

        AddTaskButton.Click += (object sender, RoutedEventArgs e) => { AddTaskButton_Click(sender, e, taskList); };
    }

    private void AddTaskButton_Click(object sender, RoutedEventArgs e, List<string> taskList)
    {
        // do something
    }
}
3
  • 3
    Remove the Click="AddTaskButton_Click" in Xaml. You are setting the handler in the code behind. Commented Feb 19, 2020 at 17:06
  • What's Tasklist with a capital T and a little l? Commented Feb 19, 2020 at 17:25
  • Does this answer your question? Adding a Parameter to a Button_Click event in WPF Commented Feb 19, 2020 at 17:43

1 Answer 1

0

Use this XAML code

<Button
x:Name="AddTaskButton"  Content="+ Add" >
</Button>

You've added an eventhander on the XAML code too. You can only add event handlers with 2 parameters: an object and a RoutedEventArgs. Your XAML code adds an other event handler to AddTaskButton_Click witch has a 3th parameter type of List<string>.

Keep the C# code as is. It adds also an event handler on the correct way using the lambda expression at the constructor. But add a semicolon where you declare taskList and change Tasklist (with a capital T and a little l) to List<string>.

Sign up to request clarification or add additional context in comments.

1 Comment

Appreciate this. I didn't realize you could specify the whole event handler in the c# file without having to do another link in the XAML file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.