Xamarin如何在按钮单击MVVM上更改背景颜色

问题描述

我试图在按下按钮时更改堆栈布局的背景颜色。这是堆栈布局:

        <StackLayout Padding="20" x:Name="LayoutTest" BackgroundColor="{Binding BackgroundTest}">
            <Label Text="Background" TextColor="Black" FontSize="Subtitle" FontAttributes="Bold" VerticalOptions="Center"></Label>
            <Frame CornerRadius="10" Padding="10" Margin="0,10" BackgroundColor="#00A6FF">
                <RadioButton GroupName="colors"></RadioButton>
            </Frame>
            <Frame CornerRadius="10" Padding="10" Margin="0,10" BackgroundColor="#13CE66">
                <RadioButton GroupName="colors" Command="{Binding ChangeBgColorGreen}"></RadioButton>
            </Frame>
            <Frame CornerRadius="10" Padding="10" Margin="0,10" BackgroundColor="#FFD185">
                <RadioButton GroupName="colors"></RadioButton>
            </Frame>
            <Frame CornerRadius="10" Padding="10" Margin="0,10" BackgroundColor="#F95F62">
                <RadioButton GroupName="colors"></RadioButton>
            </Frame>
            <Button Text="Change Color" Command="{Binding ChangeColor}"></Button>
        </StackLayout>

这是我的视图模型:

class SettingsPageviewmodel : Baseviewmodel
{
    public String BackgroundTest { get; set; }
    public Command ChangeColor { get; }
    public SettingsPageviewmodel()
    {
        Title = "Dashboard ";

        ChangeColor = new Command(ChangeBgColor);
    }
    void ChangeBgColor()
    {
        BackgroundTest = "#F95F62";
    }
}

但是,无论何时单击ChangeColor按钮,它似乎都不会更改'BackgroundTest'值。我对MVVM还是很陌生,所以不确定如何做到最好。任何帮助将不胜感激。

解决方法

在按钮中传递命令参数,并从堆栈中删除颜色绑定

<StackLayout Padding="20" x:Name="LayoutTest">
...
<Button Text="Change Color" Command="{Binding ChangeColor}" CommandParameter="{x:Reference LayoutTest}"></Button>

在ViewModel中捕获参数

ChangeColor = new Command<object>(ChangeBgColor);
...
void ChangeBgColor(object obj)
{
   if(obj is StackLayout sl)
   {
       sl.BackgroundColor = Color.FromHex("#F95F62");
   }
}

这是一种简便快捷的方法,至于为什么您的代码无法正常工作,您可以尝试两种方式的绑定模式

BackgroundColor =“ {Binding BackgroundTest, Mode =” TwoWay“ }”

如果仍然无法正常工作,则需要提高此 BackgroundTest 属性 https://www.c-sharpcorner.com/article/simplifying-mvvm-inotifypropertychanged-on-xamarin-forms/

,

您的SettingsPageViewModel不会在BackgroundTest属性上引发属性更改的通知,因此,与该属性绑定的视图将永远不会收到更新的通知。

由于您是从BaseViewModel继承的,因此您似乎正在使用MVVM框架。通常,在这些框架中,可以调用一些辅助方法来引发属性更改事件。不知道您正在使用哪个框架,我无法确切告诉您在这里要调用什么,但是在 Prism 中,它称为SetProperty,其工作方式如下:

class SettingsPageViewModel : BaseViewModel
{
    private string _backgroundTest;
    public string BackgroundTest
    {
        get => _backgroundTest;
        set => SetProperty(ref _backgroundTest,value);
    }

    public Command ChangeColor { get; }

    public SettingsPageViewModel()
    {
        Title = "Dashboard ";

        ChangeColor = new Command(ChangeBgColor);
    }

    void ChangeBgColor()
    {
        BackgroundTest = "#F95F62";
    }
}