WPF C# button click event in code behind
29,602
Solution 1
Like that:
Button btn1 = new Button();
btn1.Content = qhm.Option1;
btn1.Click += btn_Click;
sp1.Children.Add(btn1);
//separate method
private void btn_Click(object sender, RoutedEventArgs e)
{
tbox.Text = qhm.Option1;
}
using lambda:
btn1.Click += (source, e) =>
{
tbox.Text = qhm.Option1;
};
you can now access local variables.
Solution 2
You can add a click event like this:
Button btn1 = new Button();
btn1.Content = qhm.Option1;
sp1.Children.Add(btn1);
btn1.Click += btn1_Click;
Than you can edit the event method to add some text to your text box.
void btn1_Click(object sender, System.Windows.RoutedEventArgs e)
{
tbox.Text = qhm.Option1;
}
Solution 3
You want to subscribe to the click event:
Button btn1 = new Button();
btn1.Content = "content";
btn1.Click+=btn1_Click;
sp1.Children.Add(btn1);
private void btn1_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("You clicked it");
}
Solution 4
..
btn1.Click += btn1_Click;
private void btn1_Click(object sender, RoutedEventArgs e)
{
...
}
Solution 5
Register a handler for the click event:
btn1.Clicked += myHandler_Click;
private void myHandler_Click(object sender, RoutedEventArgs e)
{
// your code
}
Author by
user2376998
Updated on July 05, 2022Comments
-
user2376998 almost 2 years
I have create a button in code behind , but how do i write their click event? is it MouseDown? like this ? Basically i want to detect if the button is being pressed then i populate a textbox with some text.
Button btn1 = new Button(); btn1.Content = qhm.Option1; sp1.Children.Add(btn1); if (btn1.MouseDown = true) { tbox.Text = qhm.Option1; }