使用MVVM更改按钮BackgroundColor

时间:2018-09-18 12:58:31

标签: c# xamarin mvvm xamarin.forms

我有两个按钮,当我单击一个按钮时,我想使用mvvm更改另一个按钮BackgroundColor 我正在尝试像这样

<StackLayout>
    <Button Text="Red" BackgroundColor="Accent" Command="{Binding ChangeButtons}" x:Name="btnRed"></Button>
    <Button Text="Blue" x:Name="btnBlue"></Button>
</StackLayout>

当我单击btnRed时,我想更改btnBlue BackgroundColor。 ModelView页面

public class ButtonColorViewModel
{
    public Command ChangeButtons
    {
        get
        {
            return new Command(() => {

               //Change here button background colors

            });
        }
    }
}

我该如何实施?

2 个答案:

答案 0 :(得分:2)

基本上像这样,您需要绑定一个color属性。您可以在命令中更改属性的值。您可以对其进行调整以适应您的需求,2、3,颜色/按钮等:

public class ButtonColorViewModel
{
    public Command ChangeButtons
    {
        get
        {
            return new Command(() => {

               //Change here button background colors
               BackgroundColorBtn1 = Color.Green; //or something
            });
        }
    }


    private _backgroundColorBtn1 = Color.White;
    public Color BackgroundColorBtn1
    {
        get { return _backgroundColorBtn1;}
        set
        {
             if (value == _backgroundColorBtn1)
                 return;

             _backgroundColorBtn1 = value;
             NotifyOnPropertyChanged(nameof(BackgroundColorBtn1));
         }
    }
}

使用XAML:

<StackLayout>
    <Button Text="Red" BackgroundColor="Accent" Command="{Binding ChangeButtons}" 
            x:Name="btnRed"></Button>
    <Button BackgroundColor="{Binding BackgroundColorBtn1}" Text="Blue" 
            x:Name="btnBlue"></Button>
</StackLayout>

答案 1 :(得分:1)

根据您对MVVM的看法,最好的选择是(尽可能)避免在ViewModel中使用UI。 在上一个答案中,使用了颜色对象。 如果要在这种情况下保留MVVM:

  • 使用OnPropertyChanged创建一个属性,例如枚举
  • 将其绑定到背景颜色按钮

  • 使用转换器将您的媒体资源转换为背景色:)

我知道这是更多东西,但更像是MVVM。

此外,如果仅停留在UI中,请转到后面的代码。 使用click并直接管理背景颜色。