更改网格背景的颜色

时间:2021-02-22 21:12:21

标签: c# xaml xamarin.forms

CollectionView 中,我希望 GestureRecognizer 事件在用户按下按钮时更改背景颜色。但是,当用户按下另一个按钮时,我希望前一个按钮恢复其原始颜色。

<CollectionView.ItemTemplate>
   <DataTemplate>
        <Grid>
          <Grid.RowDefinitions>
           <RowDefinition Height="12"/>
           <RowDefinition Height="24"/>
          </Grid.RowDefinitions>
        <Grid.GestureRecognizers>
        <TapGestureRecognizer Tapped="SelectedDate_Tapped"/>
        </Grid.GestureRecognizers>
          <Label Grid.Row="0" HorizontalTextAlignment="Center" Text="{Binding Giorno}" TextColor="White" FontSize="10"/> 
     </Grid>
    </DataTemplate>
  </CollectionView.ItemTemplate>


private void SelectedDate_Tapped(object sender, EventArgs e)
        {
            var model = (Grid)sender;
            model.BackgroundColor = Color.Blue;
        }

用我的代码它会改变颜色,但它永远不会回到原来的颜色

1 个答案:

答案 0 :(得分:0)

跟踪最后选择的Grid

Grid last = null;

private void SelectedDate_Tapped(object sender, EventArgs e)
{
   var model = (Grid)sender;
   model.BackgroundColor = Color.Blue;

   if (last != null) last.BackgroundColor = myDefaultColor;

   last = model;
}