通过在其他页面上单击其他按钮来更改按钮背景颜色

时间:2020-07-06 04:39:16

标签: c# xamarin.forms

我正在尝试完成一项使我感到烦恼的任务。我要在2个不同的页面上有2个按钮,我想要实现这一点;当按下第二页上的按钮时,更改第一页上的按钮的背景颜色。例: 第一页:

<Stacklayout>
  <Button Text="Task 1"
          x:Name = "firstPage"
          BackgroundColor = "Red" />
</Stacklayout>

第二页:

<Stacklayout>
  <Button Text="Completed"
          x:Name = "secondPage"
          Clicked = "ChangeColourForFirst" />
</Stacklayout>

1 个答案:

答案 0 :(得分:1)

最简单的解决方案是单击按钮时,使用 MessagingCenter 发送通知。

在第一页

public MainPage()
    {
        InitializeComponent();

        MessagingCenter.Subscribe<Object, Color>(this, "changeColor", (arg,color) => {

            firstPage.BackgroundColor = color;


        });

    }

在第二页

private void ChangeColourForFirst(object sender, EventArgs e)
{
    MessagingCenter.Send<Object, Color>(this, "changeColor", Color.Red); // send the bgcolor that you want to change
}