How to fire a button Click event in code behind in

2019-05-01 15:12发布

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

1条回答
相关推荐>>
2楼-- · 2019-05-01 16:09

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.

查看更多
登录 后发表回答