Trigger PropertyChanged of indexed property in Xamarin Forms

By | April 20, 2017

Xamarin Forms supports binding to indexed properties. But do you know how to trigger a PropertyChanged event on such a property so that the binding engine gets the updated value?

Binding to indexed properties

Binding to an indexed property in Xamarin Forms is simple. Imagine my ViewModel has an indexed property:

I can simply bind to it using the following syntax: <Label Text="{Binding [123]}" />  where 123 is the index I pass to the property.

Notifying the UI

If I now update the underlying data collection (for example: Data["123"] = "Ninjas"; ), my UI won’t be notified about this change. However, I can notify my UI by triggering the PropertyChanged event, passing ‘Item‘ as property name:

You can also use the following syntax if you only want to notify the UI about one particular element that has changed:

Easy, right? You just have to know it… 😉

 

If you want to try it our yourself, here is the complete code:

 

 

4 thoughts on “Trigger PropertyChanged of indexed property in Xamarin Forms

  1. Pingback: Dew Drop - April 20, 2017 (#2462) - Morning Dew

  2. Pingback: Dynamically binding RESX Resources in Xamarin Forms | Pie Eating Ninjas' Blog

  3. HARI RAJAGOPAL

    Hi Pieter,
    Thanks for this tip and the complete sample code, came in handy.

    Follow up question,
    Is there a way to bind to more than one indexed property in a viewmodel?

    Indexer argument can be overloaded but the xaml is only going to pass in a string, so I am not sure how more than one indexer can be present in a view model.

    Your thoughts appreciated,

    Thanks
    Hari

    Reply
    1. PieEatingNinjas Post author

      Hi Hari,

      I’m afraid that this is not possible. You could perfectly well define a second indexed property (int as indexer argument), but the binding engine won’t know which indexed property to pick, resulting in a runtime exception.

      Glad my post could be of any help to you!

      Reply

Leave a Reply