Xamarin标签单击更改复选框"仅状态Xaml"



我正在尝试更改Xamairn中复选框的状态。

我的Xaml代码

<StackLayout Orientation="Horizontal">
<CheckBox VerticalOptions="Start"
IsChecked="{Binding IsChecked,Mode=TwoWay}">
<CheckBox.Margin>
<OnPlatform x:TypeArguments="Thickness">
<On Platform="iOS" Value="0,-10,0,0" />
<On Platform="Android, WinPhone, Windows" Value="0,-5,0,0" />
</OnPlatform>
</CheckBox.Margin>
</CheckBox>
<Label VerticalTextAlignment="Center" VerticalOptions="Start"
Text="{Binding Text}">
<Label.GestureRecognizers>
<TapGestureRecognizer>
</TapGestureRecognizer>
</Label.GestureRecognizers>
</Label>
</StackLayout>

我知道我以前做过,但我忘了。

我必须在TapGestureRecognizer中添加一个setter或其他东西,以使复选框IsChecked=True并且当其True 时IsChecked=False

要以MVVM的方式实现这一点,您要寻找的是Command

在ViewModel中添加命令:

public ICommand ChangeStateCommand { get; set; }

并且在构造函数中初始化它:

ChangeStateCommand = new Command(() => IsChecked = !IsChecked);

然后,您需要将其与LabelTapGestureRecognizer绑定。

<StackLayout Orientation="Horizontal" VerticalOptions="CenterAndExpand">
<CheckBox VerticalOptions="Start"
IsChecked="{Binding IsChecked,Mode=TwoWay}">
<CheckBox.Margin>
<OnPlatform x:TypeArguments="Thickness">
<On Platform="iOS" Value="0,-10,0,0" />
<On Platform="Android, WinPhone, Windows" Value="0,-5,0,0" />
</OnPlatform>
</CheckBox.Margin>
</CheckBox>
<Label VerticalTextAlignment="Center" VerticalOptions="Start"
Text="{Binding Text}" >
<Label.GestureRecognizers>
<TapGestureRecognizer Command="{Binding ChangeStateCommand}" />
</Label.GestureRecognizers>
</Label>
</StackLayout>

希望这能有所帮助。-

给checkBox一个名称,给标签一个tapEvent,然后在代码后面更改isChecked属性:

<StackLayout Orientation="Horizontal">
<CheckBox VerticalOptions="Start" x:Name="myCheckBox"
IsChecked="{Binding IsChecked,Mode=TwoWay}">
<CheckBox.Margin>
<OnPlatform x:TypeArguments="Thickness">
<On Platform="iOS" Value="0,-10,0,0" />
<On Platform="Android, WinPhone, Windows" Value="0,-5,0,0" />
</OnPlatform>
</CheckBox.Margin>
</CheckBox>
<Label VerticalTextAlignment="Center" VerticalOptions="Start"
Text="{Binding Text}">
<Label.GestureRecognizers>
<TapGestureRecognizer Tapped="TapGestureRecognizer_Tapped">
</TapGestureRecognizer>
</Label.GestureRecognizers>
</Label>
</StackLayout>

在代码背后:

private void TapGestureRecognizer_Tapped(object sender, EventArgs e)
{
myCheckBox.IsChecked = !myCheckBox.IsChecked;
//or change the IsChecked property in ViewModel
//myViewModel.IsChecked = !myViewModel.IsChecked;
}

最新更新