Friday, August 7, 2015

Change Grid/Button Background color through MVVM pattern in Windows Phone

Problem:


Having completed an iPhone app using an MVVMCross core backend.  I need to create the windows phone version UI for the backend.  The iPhone app uses the SegmentControl on a view.  The iPhone app works great and seemlessly with the core.  Now windows phone does not have a segement control per se.  You could simply use a hub/tiles or panorama control templates.  The customer however is very enamored of  the look an feel of the Segment Control.  So it was off too Xaml and blend to build out a similar control.  This I accomplished pretty quickly. 

The issue is the binding to the modelview.  Their is no command property on the grid; however the button control does.  So how to get the interaction to bind with the model view?  Fortunately we have the iValueConverter in the UI layer.  This allows us to bind to properties in the xaml controls.  This combined with model view can allow us to get the functionality to match the segmentcontrol.

Solution:


modelview

private Cirrious.MvvmCross.ViewModels.MvxCommand _myCommand
public ICommand MyCommand
{
             get
            {
                  _myCommand = _myCommand ?? new Cirrious.MvvmCross.ViewModels.MvxCommand(DoMyCommand);
                   return _myCommand;
            }

}

private void DoMyCommand()
{
             ISActive = true;
}


private bool _isActive;

public bool ISActive
{
         get
         { return _isActive;}
         set { _isActive = value;
             RaisePropertyChanged()) => ISActive);
        }

}

view (xaml)

xmlns:phone="clr-namespace:Microsoft.Phone.Controls..."
xmlns:local="clr-namespace:MyNamespace"

<phone:PhoneApplicationPage.Resources>
<local:BrushColorConverter x:Key="ColorConverter" />
</phone:PhoneApplicationPage.Resources>
......

<Grid
Background={Binding ISActive Converter={StaticResource ColorConverter}}
....>
<Button
Background={Binding ISActive Converter={StaticResource ColorConverter}}
Command="{Binding MyCommand}"
.....
/>

</Grid>


(BrushColorConverter.cs (separate class file) in UI project)
 public class ColorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value == null)
        {
            return new SolidColorBrush(Colors.Transparent);
        }
        return System.Convert.ToBoolean(value) ?
            new SolidColorBrush(Colors.Red)
          : new SolidColorBrush(Colors.Transparent);
    }
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}




Source:
  1. http://stackoverflow.com/questions/7329812/change-button-background-color-through-mvvm-pattern-in-wpf
  2. http://www.codeproject.com/Articles/758656/Use-Converters-in-your-Windows-Phone-Apps

No comments:

Post a Comment