在 Xamarin 中单击时如何更改按钮颜色

How to change button color when it is clicked in Xamarin

我是 xamarin 的新手,我正在尝试向我的按钮添加点击事件。所以这是我的 4 个按钮:

<StackLayout HorizontalOptions="Center" VerticalOptions="Center">
                    <Button Text="Page 1" TextColor="#EEF2FF" FontSize="20" HorizontalOptions="Center" BackgroundColor="#FF5959" />
                </StackLayout>
                <StackLayout Grid.Column="1" HorizontalOptions="Center" VerticalOptions="Center">
                    <Button Text="Page 2" Clicked="Handle_Page" TextColor="#676FA3" FontSize="20" HorizontalOptions="Center" BackgroundColor="#EEF2FF"/>
                </StackLayout>
                <StackLayout Grid.Column="2" HorizontalOptions="Center" VerticalOptions="Center">
                    <Button Text="Page 3" TextColor="#676FA3" FontSize="20" HorizontalOptions="Center" BackgroundColor="#EEF2FF"/>
                </StackLayout>
                <StackLayout Grid.Column="3" HorizontalOptions="Center" VerticalOptions="Center">
                    <Button Text="Page 4" TextColor="#676FA3" FontSize="20" HorizontalOptions="Center" BackgroundColor="#EEF2FF"/>
                </StackLayout>

所以按钮的颜色是#EEF2FF,但是当我点击按钮时,我希望将其更改为#FF5959。但是如果已经点击了另一个按钮,那么它也应该更改为主要颜色#EEF2FF。这样我们就可以cay同步点击事件了。

我是新手,如有任何帮助,我们将不胜感激。

添加点击处理程序

<Button Clicked="ButtonClicked" ... />

然后在处理程序中

protected void ButtonClicked(object sender, EventArgs args)
{
  // set the other buttons back to the base color
  // you will need to assign each button an x:Name in xaml
  btn1.BackgroundColor = Color.FromHex("EEF2FF");
  ...
  btn10.BackgroundColor = Color.FromHex("EEF2FF");

  // then change the color of only the selected button
  var btn = (Button)sender;
  btn.BackgroundColor = Color.FromHex("FF5959");
} 
protected override void OnCreate(Bundle savedInstanceState)
{   
    ScreenClickButton.Click += ChangeColorToRed;
}

private void ChangeColorToRed(object sender, EventArgs e)
{
    ScreenClickButton.SetBackgroundColor(color: Color.Red);
}