Search code examples
c#xamarinmvvmcross

BackgroundColor Binding in MvvmCross


I am trying to change the background color of the spinner with binding BackgroundColor property in as follows, but it is having no effect.

View.axml

<mvvmcross.droid.support.v7.appcompat.widget.MvxAppCompatSpinner
    android:layout_width="115dp"
    android:layout_height="match_parent"
    android:textColor="@color/primary_text"
    local:MvxItemTemplate="@layout/single"
    local:MvxBind="ItemsSource SingleList; SelectedItem SingleSize ; BackgroundColor SingleBackgroundValueConverter(IsSingleValid)" />

Converter.cs

public class SingleBackgroundValueConverter: MvxValueConverter<bool>
{
  protected override MvxColor Convert(bool value, object parameter, CultureInfo culture)
  {
    // either white or red
    return value ? new MvxColor(255, 255, 255) : new MvxColor(255, 0, 0);
  }
}

In the following, I was able to see the alert pop up, but background color does not change at all.

ViewModel.cs

public void Save()
{
    if (!isExist)
    {
         OnExit(this, null);
    }
    else
    {
        _isSingleValid= false;
        RaisePropertyChanged(() => IsSingleValid);
        Mvx.Resolve<IUserDialogs>().Alert("It is not valid");
    }
}

private bool _isSingleValid = true;
public bool IsSingleValid
{
    get { return _isSingleValid; }
    set
    {
        _isSingleValid= value;
        RaisePropertyChanged(() => IsSingleValid);
    }
}

Solution

  • BackgroundColor is part of the Color pluign.

    The first step is to make sure you have installed it.

     Install-Package MvvmCross.Plugin.Color
    

    And then inherit your converter from MvxColorValueConverter<T>.

    public class SingleBackgroundValueConverter : MvxColorValueConverter<bool>
    {
        protected override MvxColor Convert(bool value, object parameter, CultureInfo culture)
        {
            return value ? new MvxColor(255, 255, 255) : new MvxColor(255, 0, 0);
        }
    }
    

    Then you have to change your converter name in the binding, because mvvmcross naming convention strips off the ValueConverter part.

    local:MvxBind="ItemsSource SingleList; SelectedItem SingleSize ; BackgroundColor SingleBackground(IsSingleValid)"