提问者:小点点

在按钮后面的代码中添加“onclick”事件


所以我创建了一个按钮,我想通过点击它来改变它的文本。

下面是我的代码(来自Page_Load代码):

Button InviteToGameBTN = new Button();
InviteToGameBTN.Click += new EventHandler(InviteToGameBTN_OnClick);

protected void InviteToGameBTN_OnClick(object sender,EventArgs e)
{
        Button b1 = (Button)sender;
        b1.Text = "Text changed";

}

会有什么不对劲? 感谢所有人。


共2个答案

匿名用户

请尝试以下操作:

public class Foo
{
    public Foo()
    {
        Button myButton = new Button();
        myButton.Content = "Old text";
        myButton.Click += ButtonClicked;
        yourGrid.Children.Add(myButton);
    }

    private void ButtonClicked(object sender, RoutedEventArgs e)
    {
        Button clickedButton = (Button) sender;
        clickedButton.Content = "New text";
    }
}

匿名用户

不确定这是否100%有效,但您可以使用InviteToGamebtn.text直接更改它:

var button = FindViewById<Button>(Resource.Id.button1);
        button.Click += delegate
        {
            button.Text = "changed text";
        };

这是我在一个新程序中做的一点,它没有使用事件处理程序,而是使用button.text通过委托{}直接更改它的属性