Guillaume
Guillaume

Reputation: 1105

How to bind an array in mvvmcross

I'm trying to make my first application using MVVMCross. It's also my first mobile application.

In my ViewModel, I have an array (stored in a custom object). Its dimensions are fixed (2 rows, 3 columns).

public Table SearchBox {get;set;}

I want to bind my six cells to six different textview (for now I'm targeting Android) I wrote a custom converter :

protected override string Convert(Table value, Type targetType, object parameter, CultureInfo culture)
        {
            string rowcol=parameter.ToString();
            int row =System.Convert.ToInt32( rowcol.Substring (0, 1));
            int col= System.Convert.ToInt32(rowcol.Substring(1,1));
            return value.CellValue(row,col);
        }

It's working correctly with this binding for each textview :

 local:MvxBind="Text SearchBox,Converter=Table,ConverterParameter='00'" 

So far, so good, and I'm quite proud of myself. Is there a better way ?

Next step is modifying the textview value (using drag and drop, but that's for another day). The prototype for ConvertBack is :

protected override Table ConvertBack(string value, Type targetType, object parameter, CultureInfo culture)

But how I can modify only one cell of my array ? Is it even possible this way ?

Before creating my converter, I was thinking of converting my array to six variables in the viewModel, which would have been obvious to two-way bind. But I'd rather use my array...

Upvotes: 1

Views: 839

Answers (1)

Stuart
Stuart

Reputation: 66882

So far, so good, and I'm quite proud of myself. Is there a better way ?

Looks good so far.

But how I can modify only one cell of my array ? Is it even possible this way ?

Technically it could be possible - eg you could do it using some custom multi-dimension source binding.

However, for a first project I wouldn't recommend this - it's a bit technical.

General C# data-binding (both MvvmCross and Xaml) do support one-dimensional lists - so you could bind to something like Text SearchBox[4] or even something like Text SearchBox[4][5] - but they don't (currently) support multi-dimensional arrays - so you can't easily do Text SearchBox[4, 5]

The reason for this is because Xaml data-binding doesn't support it - see "Indexer" in http://msdn.microsoft.com/en-us/library/cc645024%28VS.95%29.aspx - and MvvmCross used this as the baseline for its code.

I suspect the easiest route forwards would be to shape your ViewModel data away from the multi-dimensional array and into a shape which is more easily consumed by the View - e.g. could you shape your data as an array of arrays rather than as a multi-dimensional array?

Upvotes: 1

Related Questions