通常每个项目都绑定一个模型,该模型包含一个保持选中或不选中的布尔值。使用这种方法,您可以根据需要初始化它们。然后创建用于点击手势的手势识别器并使用触发器进行选择效果(背景颜色)
(在您的定义中,您提到在 Grid 内部使用,所以我没有为 UI 层次结构提供新方法)
代码如下:
型号:
public Class ItemModel: INotifyPropertyChanged
{
// implement INotifyPropertyChanged interface
public ItemModel()
{
ToggleCommand = new Command(CmdToggle);
}
private void CmdToggle()
{
IsSelected = !IsSelected;
}
public string Name
{
get;
set; //call OnPropertyChanged
}
public bool IsSelected
{
get;
set; //call OnPropertyChanged
}
public ICommand ToggleCommand{get;private set;}
}
视图模型
public Class PageViewModel: INotifyPropertyChanged
{
public List<ItemModel> Items
{
get;
set; //call OnPropertyChanged
}
}
转换器
public class BoolToColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is bool)
return ((bool)value) ? Color.Gray: Color.White;
else
throw new NotSupportedException();
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
}
Xaml:
<Page.Resources>
<Color x:Key="SelectedColor">Gray</Color/>
<Color x:Key="UnselectedColor">White</Color/>
<namespace:BoolToColorConverter x:Key="BoolToColorConverter"/>
</Page.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="90"/>
<RowDefinition Height="90"/>
<RowDefinition Height="90"/>
<RowDefinition Height="90"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<!--Single item -->
<StackLayout Grid.Row="0"
Grid.Column="0"
BindingContext="{Binding Items[0]}"
Orientation="Vertical"
BackgroundColor="{Binding IsSelected,Converter={StaticResource BoolToColorConverter}}"
>
<Image Source="{Binding yourImageProperty}" />
<Image Source="{Binding yourImage2Property}" />
<Label Source="{Binding Name}"/>
<StackLayout.GestureRecognizers>
<TapGestureRecognizer Command="{Binding ToggleCommand}" />
</StackLayout.GestureRecognizers>
<!--Triggers will update background color when update IsSelected-->
<StackLayout.Triggers>
<DataTrigger TargetType="StackLayout" Binding="{Binding IsSelected}" Value="True">
<Setter Property="BackgroundColor" Value="{StaticResource SelectedColor}" />
</DataTrigger>
<DataTrigger TargetType="c:Label" Binding="{Binding IsSelected}" Value="False">
<Setter Property="BackgroundColor" Value="{StaticResource UnselectedColor}" />
</DataTrigger>
</StackLayout.Triggers>
</StackLayout>
</Grid>