Wednesday, October 17, 2012

How to bind an Android ImageView to an image loaded from Monodroid Assets

From StackOverflow 

Quick answer:

  • if your Android image file is stored in assets/images/i1.png
  • then make sure it is marked as an AndroidAsset
  • then your path needs to be images/i1.png

Longer answer:

Ideally your ViewModel should be platform independent and not know about View concerns.

So your ViewModel might perhaps expose a property like:

 private GameState _state;
public GameState State
{ return _state; }
{ _state = value; RaisePropertyChanged(() => State); }

where GameState is an enumeration like:

 public enum GameState

you might then have images representing these states in an assets structure like:


where each of those files is marked with BuildAction of AndroidAsset.

To then display the correct image in the UI, you would need a value converter like:

public class GameStateConverter
: MvxBaseValueConverter
public override object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
return string.Format("gamestates/{0}.png", ((GameState)value).ToString().ToLower());

mapped in using a Converters wrapper like:

public class Converters
public readonly GameStateConverter GameState = new GameStateConverter();

which is configured in setup.cs using:

    protected override IEnumerable<Type> ValueConverterHolders
{ return new[] { typeof(Converters) }; }

With this in place, then your axml binding statement would be:

    {'AssetImagePath':{'Path':'State', 'Converter':'GameState'}}

For an alternative approach using resources instead of assets, see MvxButtonIconBinding in –Üssue with binding to GridLayout to Android

No comments:

Post a Comment