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

做~自己de王妃 提交于 2019-12-07 07:01:36

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/3587412/how-to-fire-a-button-click-event-in-code-behind-in-user-control

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!