Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fire a button Click event in code behind in user control?

is it possible to fire a button Click event in code behind in user control?

like image 397
KentZhou Avatar asked Aug 27 '10 19:08

KentZhou


People also ask

How do you call a Button click event from code behind?

Solution 3 Hi, Button event is always trigger when you click the button but if you want to raise your button click event manually from code then you can use Button. PerformClick() from your code. Suppose on click of your Button1 you want to trigger Button2 click event then Please refer this[^] MSDN example.

How do I create a Button click event?

You could write 25 delegates or use a loop to handle the click event. public form1() { foreach (Panel pl in Container. Components) { pl. Click += Panel_Click; } } private void Panel_Click(object sender, EventArgs e) { // Process the panel clicks here int index = Panels.

Which method is used for Click event of a Button to execute some action?

To make click event work add android:onClick attribute to the Button element in your XML layout. The value for this attribute must be the name of the method you want to call in response to a click event.

Which event is raised when a user clicks a Button?

The Click event is raised when the Button control is clicked. This event is commonly used when no command name is associated with the Button control (for instance, with a Submit button). For more information about handling events, see Handling and Raising Events.


1 Answers

In C# events can only be invoked from the class that declares them. In case of the Button there is a method called OnClick which raises the ClickEvent but it is protected. So you need to declare class that inherits from Button and change the visibility of OnClick method (or declare some over method that calls base.OnClick)

public class MyButton : Button
{
    public new void OnClick()
    {
        base.OnClick();
    }
}

Example of XAML

<StackPanel Background="White" >
    <my:MyButton x:Name="TestButton" Click="HandleClick" Content="Test" />
    <TextBlock x:Name="Result" />
</StackPanel>

And code behind:

public partial class MainPage : UserControl
{
    public MainPage()
    {
        InitializeComponent();
        new Timer(TimerCall,null,0,1000);
    }

    private void TimerCall(object state)
    {
        Dispatcher.BeginInvoke(()=>TestButton.OnClick());
    }

    private void HandleClick(object sender, RoutedEventArgs e)
    {
        Result.Text = String.Format("Clicked on {0:HH:mm:ss}",DateTime.Now);
    }
}

Though it is always easier to call event handler directly.

HandleClick(this,null)

Then there will be no need for extra plumbing.

like image 169
Bulat Avatar answered Jan 04 '23 18:01

Bulat