我正在Xamarin中为UWP创建一个表单,我有这样的代码:
XAML
<StackLayout Orientation="Horizontal" HorizontalOptions="CenterAndExpand">
<Label Text="My Checkbox"
VerticalOptions="Center"
TextColor="White"></Label>
<CheckBox x:Name="myCheckbox"
WidthRequest="150"
VerticalOptions="Center"
Color="#ff914d"
CheckedChanged="Check_Changed"></CheckBox>
<Label Text="Other Checkbox"
VerticalOptions="Center"
TextColor="White"></Label>
<CheckBox x:Name="otherCheckbox"
WidthRequest="150"
VerticalOptions="Center"
Color="#ff914d"
CheckedChanged="Check_Changed"></CheckBox>
</StackLayout>
在我的CS中:(GET_FIELD_NAME在我的代码中不是这样的,我要求一个方法来实现这一点(
void Check_Changed(object sender, CheckedChangedEventArgs e)
{
switch( GET_FIELD_NAME )
{
case myCheckbox :
// Update myCheckbox var
case otherCheckbox :
// Update otherCheckbox var
etc.
}
}
因为我有很多复选框,所以我不想要很多不同的方法,而是一个带开关的方法,用getted名称更新正确的var。我查看了"发件人"属性,但一无所获。。。我如何获得这些信息:所有只使用一种方法点击的x:Name字段
谢谢你的帮助^^(对不起,英语不是我的母语(
更好的方法是定义一个附加的Tag
BindableProperty,类似于UWP平台控件。并使用以下taghelper在xaml中指定每个具有标记值的CheckBox。
附加类
public class TagHelper
{
public static readonly BindableProperty TagProperty = BindableProperty.Create("Tag", typeof(string), typeof(TagHelper), null);
public static string GetTag(BindableObject bindable)
{
return (string)bindable.GetValue(TagProperty);
}
public static void SetTag(BindableObject bindable, string value)
{
bindable.SetValue(TagProperty, value);
}
}
用法
<StackLayout HorizontalOptions="CenterAndExpand" Orientation="Horizontal">
<Label
Text="My Checkbox"
TextColor="White"
VerticalOptions="Center" />
<CheckBox
x:Name="myCheckbox"
local:TagHelper.Tag="myCheckbox"
CheckedChanged="Check_Changed"
VerticalOptions="Center"
WidthRequest="150"
Color="#ff914d" />
<Label
Text="Other Checkbox"
TextColor="White"
VerticalOptions="Center" />
<CheckBox
x:Name="otherCheckbox"
local:TagHelper.Tag="otherCheckbox"
CheckedChanged="Check_Changed"
VerticalOptions="Center"
WidthRequest="150"
Color="#ff914d" />
</StackLayout>
代码隐藏使用GetTag
方法检索标记值。
private void Check_Changed(object sender, CheckedChangedEventArgs e)
{
var checkbox = sender as CheckBox;
var tag = TagHelper.GetTag(checkbox);
switch (tag)
{
case "myCheckbox":
break;
case "otherCheckbox":
break;
default:
break;
}
}