Reputation: 407
I am trying to change the state of a Checkbox in Xamairn.
My Xaml Code
<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>
I know I have done this before but I forgot.
I have to add a setter or something in the TapGestureRecognizer to make the Checkbox IsChecked=True and IsChecked=False when its True
Upvotes: 3
Views: 4712
Reputation: 15786
Give a name to checkBox and a tapEvent to label, then change the isChecked property in code behind:
<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>
And in code behind:
private void TapGestureRecognizer_Tapped(object sender, EventArgs e)
{
myCheckBox.IsChecked = !myCheckBox.IsChecked;
//or change the IsChecked property in ViewModel
//myViewModel.IsChecked = !myViewModel.IsChecked;
}
Upvotes: 0
Reputation: 9346
To do it in an MVVM way what you are looking for is the Command
.
In your ViewModel add the command:
public ICommand ChangeStateCommand { get; set; }
and in the Constructor initialize it:
ChangeStateCommand = new Command(() => IsChecked = !IsChecked);
Then you will need to bind it with the TapGestureRecognizer
of your Label
.
<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>
Hope this helps.-
Upvotes: 6