logiseye
logiseye

Reputation: 21

How do you Bind an Image to the HighlightedImage-Property of an ImageView?

I'm currently trying to bind two images to an iOS ImageView via MvvmCross. One should be displayed when the ImageView is in 'default' state, the other one when the ImageView is highlighted.

By the following code I can bind the Image for the default state. But how do I bind the one for 'highlighted' state?

public CategoryCell(IntPtr handle): base(string.Empty, handle)
{
    _imageViewLoader = new MvxImageViewLoader(() => this.imageView);
    this.DelayBind(() =>
    {
        var set = this.CreateBindingSet<CategoryCell, MaterialCategory>();
        set.Bind(titleLabel).To(materialCategory => materialCategory.Label);
        set.Bind(_imageViewLoader).To(materialCategory => materialCategory.ImageActiveUri);
        set.Bind(this).For(cell => cell.Selected).To(materialCategory => materialCategory.IsSelected);
        set.Apply();
    });
}

Upvotes: 0

Views: 1279

Answers (2)

WickedW
WickedW

Reputation: 2601

Another approach if you do not need image loading i.e. for lots of static UX.

You can set up as follows -

_imageView = new UIImageView(UIImage.FromFile("some/image/off.png"))
        {
            HighlightedImage = UIImage.FromFile("some/image/on.png")
        };

And bind it e.g. an "Enabled" Property -

this.DelayBind(() =>
        {
            var set = this.CreateBindingSet<SomeView, SomeViewModel>();

            set.Bind(_imageView).For(v => v.Highlighted).To(vm => vm.Enabled);

            set.Apply();
        });

And don't forget to add Highlighted to your LinkerPleaseInclude.cs.

Hope this helps

Upvotes: 1

Sven-Michael St&#252;be
Sven-Michael St&#252;be

Reputation: 14750

I think the best solution is to introduce an extra property ImageUri. In the setter of your IsSelected you set the ImageUri dependend on the selection state.

ViewModel:

public class MaterialCategory : MvxViewModel
{
    //...
    public string ImageActiveUri { ... } // call UpdateImageUri() here, too
    public string ImageInactiveUri { ... } // call UpdateImageUri() here, too
    public string ImageUri { ... }
    public bool IsSelected 
    {
        get { return _isSelected; }
        set 
        {
            _isSelected = value;
            UpdateImageUri();
            RaisePropertyChanged(() => IsSelected);
        }
    }   

    private void UpdateImageUri() 
            {
        ImageUri = IsSelected ? ImageActiveUri : ImageInactiveUri;
    }
}

Binding:

set.Bind(_imageViewLoader).To(materialCategory => materialCategory.ImageUri);
// instead of:
// set.Bind(_imageViewLoader).To(materialCategory => materialCategory.ImageActiveUri);

Upvotes: 0

Related Questions