Reputation: 5
I am coding in Visual Studio 2017 and using Xamarin.Forms.
I can bind the "Text" properties of labels and buttons to strings, use INotifyPropertyChanged and also implement the Command interface for my buttons, cool, it all works fine and dandy.
I have a collection in my ViewModel which is essentially a class referenced by my View which is a XAML page.
What I am trying to do now is Bind a label to a specific index of my collection of strings.
So I have this in the VM (c# class)
public List<string> MessageCollection;
And this in the View (XAML Content page)
<Label Text="{Binding MessageCollection}"/>
I have googled for a while and checked other questions here on Stack-O but have not found a definitive answer to my question.
What I want to do is something like this:
<Label Text="{Binding MessageCollection[0]}"/>
or
<Label Text="{Binding MessageCollection, Index="0"}"/>
proceeding with
<Label Text="{Binding MessageCollection[0]}"/>
<Label Text="{Binding MessageCollection[1]}"/>
<Label Text="{Binding MessageCollection[2]}"/>
and so on.
The List will be modified at runtime as users can add and remove strings and edit the content of those strings via buttons and entryfields.
What is a good way to reference the collection by index in a binding expression?
Upvotes: 0
Views: 1723
Reputation: 472
Try using converter as below...
public class ListToFirstObjectGetter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is System.Collections.IList list)
{
return list[0];
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Upvotes: 1
Reputation: 1089
you can try in the following formate.
Sample code
List<string> messageCollection;
string message = string.empty;
message = messageCollection.indexOf(your specific index no);
From the above code, you can retrieve the specific string from your message collection. now you can bind 'message' string to your view.
Upvotes: 0
Reputation: 89214
This syntax should work
<Label Text="{Binding MessageCollection[0]}"/>
However, you can only bind to public properties, so you need to declare MessageCollection
with a getter
public List<string> MessageCollection { get; set; }
Upvotes: 0