Binding to a specific element of an array (or List)

DR_BartDR_Bart Member ✭✭
edited December 2018 in Xamarin.Forms

After much googling, I haven't found an answer to this.

I have an array of colors. I want to bind a Button's BorderColor to a specific element within an array.
What is the syntax to achieve this?

Xaml:

 BorderColor="{Binding ButtonColors[11], Converter={Services:ByteToBorderColourConverter}}"

ViewModel:

private List<byte> buttoncolors;

public List<Byte> ButtonColors
    {
        get => buttoncolors;
        set
        {
            buttoncolors = value;
            OnPropertyChanged();
        }
    }

...

ButtonColors[11] = (Byte)Data[3];

I've also tried implementing this with byte[] array (which I would prefer), but it also doesn't work.
I think the xaml binding syntax is incorrect maybe?

Tagged:

Answers

  • JohnHJohnH GBMember ✭✭✭✭✭

    @DR_Bart said:

    My suggestion would be not to build logic into the binding but create a property on your model that references the appropriate element of the array.

  • ClintBClintB Member ✭✭

    Your best bet, as @JohnHair said, is to make a property to bind to. Assuming you're working with the MVVM design pattern, have the logic of getting that Color from your array, or list, in your ViewModel. Then take that Color and put it in a property that your View can bind to.

Sign In or Register to comment.