我遇到了一个不知道如何解决的问题。我的困难来自于以下几点: 我的视图如下所示:
现在,这三个相同的结构由一个 CollectionView 表示。这些开关绑定到名为
IsCorrect
的特定于对象的布尔属性,用户可以通过 XAML 中的 IsToggled
进行调整:
<Switch IsToggled="{x:Binding IsCorrect, Mode=TwoWay}" />
我现在的困难来自于开关的预期行为:我想实现它,如果我例如将第二个答案切换为“打开”,第一个答案关闭。换句话说,只有一个正确答案。
现在,我不明白在使用Community Toolkit时如何将特定CollectionView对象的信息传播到ViewModel相应的开关命令。我需要使用
RelayCommand<T>
吗?如何才能实现这一目标?
根据要求:
CollectionView 的 XAML:
<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>
这是
Answer
模型:
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; }
}
我已经解决了类似的问题,当您将对象添加到集合视图时,订阅属性更改事件,主要是“IsCorrect”属性更改。
现在,当调用此函数时,您可以关闭(设置为 false?)集合视图项中的其他 IsCorrect。