如何使用代码隐藏在 Xamarin.Forms 中创建按钮单击事件处理程序?
How to create a button clicked EventHandler in Xamarin.Forms with code-behind?
我想让用户点击我的主页上的添加术语按钮来创建新的术语页面。我想要创建一个按钮来导航到该术语。我已经创建了按钮来添加术语,但我无法弄清楚如何为新创建的按钮提供一个用于导航的事件处理程序。这是我目前所拥有的:
private string crrntTerm;
private List<Term> termList;
private void addTermBtnForTest()
{
Term termTest = new Term()
{
TermTitle = "Term 1",
CreateDate = System.DateTime.Now
};
using (SQLiteConnection conn = new SQLiteConnection(App.FilePath))
{
conn.CreateTable<Term>();
conn.Insert(termTest);
crrntTerm = termTest.TermID.ToString();
termList = conn.Table<Term>().ToList();
}
Button testBtn = new Button()
{
TextColor = Color.Black,
FontAttributes = FontAttributes.Bold,
FontSize = 20,
Margin = 30,
BackgroundColor = Color.White,
Clicked += GoToTermButton_Clicked //Error: Invalid initializer member declarator
};
testBtn.BindingContext = termTest;
testBtn.SetBinding(Button.TextProperty, "TermTitle");
layout.Children.Add(testBtn);
}//end addTermBtnForTest
private async void GoToTermButton_Clicked(object sender, EventArgs e)
{
// Code to go to appropriate page
}
如果您在初始化按钮后添加事件,它不会报错。
Button testBtn = new Button()
{
TextColor = Color.Black,
FontAttributes = FontAttributes.Bold,
FontSize = 20,
Margin = 30,
BackgroundColor = Color.White,
};
testBtn.Clicked += async (sender, args) =>{....}
//testBtn.Clicked += async (sender, args) => GoToTermButton_Clicked (sender,args);
我想让用户点击我的主页上的添加术语按钮来创建新的术语页面。我想要创建一个按钮来导航到该术语。我已经创建了按钮来添加术语,但我无法弄清楚如何为新创建的按钮提供一个用于导航的事件处理程序。这是我目前所拥有的:
private string crrntTerm;
private List<Term> termList;
private void addTermBtnForTest()
{
Term termTest = new Term()
{
TermTitle = "Term 1",
CreateDate = System.DateTime.Now
};
using (SQLiteConnection conn = new SQLiteConnection(App.FilePath))
{
conn.CreateTable<Term>();
conn.Insert(termTest);
crrntTerm = termTest.TermID.ToString();
termList = conn.Table<Term>().ToList();
}
Button testBtn = new Button()
{
TextColor = Color.Black,
FontAttributes = FontAttributes.Bold,
FontSize = 20,
Margin = 30,
BackgroundColor = Color.White,
Clicked += GoToTermButton_Clicked //Error: Invalid initializer member declarator
};
testBtn.BindingContext = termTest;
testBtn.SetBinding(Button.TextProperty, "TermTitle");
layout.Children.Add(testBtn);
}//end addTermBtnForTest
private async void GoToTermButton_Clicked(object sender, EventArgs e)
{
// Code to go to appropriate page
}
如果您在初始化按钮后添加事件,它不会报错。
Button testBtn = new Button()
{
TextColor = Color.Black,
FontAttributes = FontAttributes.Bold,
FontSize = 20,
Margin = 30,
BackgroundColor = Color.White,
};
testBtn.Clicked += async (sender, args) =>{....}
//testBtn.Clicked += async (sender, args) => GoToTermButton_Clicked (sender,args);