I've run into a problem I don't know how to solve. My difficulty arises from the following: My View looks like the following:
Now, the three identical structures are represented by a CollectionView. The switches are bound to an object-specific boolean property named IsCorrect
, which is adjusted by the user via IsToggled
in the XAML:
<Switch IsToggled="{x:Binding IsCorrect, Mode=TwoWay}" />
My difficulty now arises from the wished behaviour of the switches: I would like to implement that if I e.g. switch the second answer to "on", the first one is turned off. In other words, there shall be one and only one correct answer.
Now, I don't understand how I may propagate the information of the specific CollectionView object to the ViewModel's corresponding switch's command while using the Community Toolkit. Do I need to use RelayCommand<T>
? How can one achieve that?
Upon request:
XAML of CollectionView:
<CollectionView.ItemTemplate>
<DataTemplate>
<Grid x:DataType="models:Answer"
Padding="20">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition />
</Grid.ColumnDefinitions>
<HorizontalStackLayout Grid.Row="0"
Grid.Column="0"
Spacing="10">
<Entry Text="{x:Binding Points}"
TextColor="{StaticResource NightBlue}"
IsSpellCheckEnabled="False"
IsTextPredictionEnabled="False"
Keyboard="Numeric"
IsVisible="{Binding
Path=BindingContext.QuestionType,
Converter={StaticResource QuestionTypeToBooleanConverter},
Source={x:Reference refCreateQuestionEditorView}}" />
<Label Text="{x:Binding IsCorrect, Converter={StaticResource IsCorrectToStringConverter}}"
TextColor="{x:Binding IsCorrect, Converter={StaticResource IsCorrectToTextColorConverter}}"
FontAttributes="Bold"
VerticalOptions="Center" />
<Switch IsToggled="{x:Binding IsCorrect, Mode=TwoWay}"
IsVisible="{Binding
Path=BindingContext.QuestionType,
Converter={StaticResource QuestionTypeToBooleanConverter},
Source={x:Reference refCreateQuestionEditorView}}" />
</HorizontalStackLayout>
<Editor Grid.Row="1"
Grid.Column="0"
AutoSize="TextChanges"
Text="{x:Binding Content, Mode=TwoWay}"
TextColor="{StaticResource NightBlue}"
BackgroundColor="{StaticResource SnowWhite}" />
</Grid>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
And here the Answer
Model:
public partial class Answer : ObservableObject
{
[Key]
public int AnswerId { get; set; }
public int QuestionId { get; set; }
public string Content { get; set; }
[ObservableProperty]
private bool _isCorrect;
public int? Points { get; set; }
[NotMapped]
public bool IsSelected { get; set; }
}
I had solved a similar issue as, When you are adding the object to the collection view, subscribe to the property changed events, mainly the "IsCorrect" property changed.
Now when this is invoked you can turn off (set false?) the other IsCorrect within the collection view items.