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

时间:2020-04-17 15:33:50

标签: xaml xamarin xamarin.forms

我正在尝试更改Xamairn中Checkbox的状态。

我的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中添加设置器或其他东西,以使Checkbox IsChecked = True 和IsChecked = False为真

2 个答案:

答案 0 :(得分:2)

要以MVVM方式进行操作,您需要的是Command

在ViewModel中添加命令:

public ICommand ChangeStateCommand { get; set; }

并在构造函数中对其进行初始化:

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

然后,您需要将其与TapGestureRecognizer的{​​{1}}绑定。

Label

希望这会有所帮助。-

答案 1 :(得分:0)

为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;
}