开发者

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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜