在Button事件处理程序方法Xamarin Forms中获取控件名称 [英] Get control name in Button event handler method Xamarin Forms
问题描述
我的Xamarin Forms应用程序中有20个按钮.所有按钮共享相同的click事件方法.我想做的是使用switch语句检查按钮名称,但是我很难找到触发事件的控件名称.
I have 20 buttons in my Xamarin Forms app . All of the buttons share the same click event method. What I want to do is use switch statement to check the button name but I am having difficulty finding the controls name that fired the event .
请查看代码:
private void btnCollection_Clicked(object sender, EventArgs args)
{
var btn = (Button)sender;
switch (btn.FindByName) // I want to get the name of the control
{
case "btn1":
break;
case "btn2":
break;
}
}
如何获取按钮的名称?
推荐答案
您不能访问xaml元素的x:Name属性,因为这只是编译器命名变量的提示.
You cannot access the x:Name property of a xaml element as this is just a hint for the compiler to name the variable.
但是,您可以做的是设置按钮的ClassId
,以便您可以在处理程序中检索它.像这样:
您的xaml:
What you can do however is to set the ClassId
of your button so that you can retrieve it in the handler. Like this:
Your xaml :
<Button ClassId="sdsd"
Clicked="Button_OnClicked"/>
您的xaml.cs
private void LoginButton_OnClicked(object sender, EventArgs e)
{
var button = (Button) sender;
var classId = button.ClassId;
}
这篇关于在Button事件处理程序方法Xamarin Forms中获取控件名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!