-3

I am using Xamrin.Forms and MVVM. For the text of a label, I want to use the value of a properto of the first element of the collection of the main object of binding. I am trying this:

<Label Text="{Binding MainObject.Colleciton[0].MyProperty}" HorizontalTextAlignment="Start" TextColor="Black" FontSize="20" />

But I get the error that tells that object reference not set to an instance of an object when I try to compile.

The odd thing is that the intellisense detect MyProperty, so I don't know why it needed to set a reference, because normally when I set the binding, I have never get the case in which is check if the object is null or not.

How could I bind the property of the first item?

Thanks.

Álvaro García
  • 18,114
  • 30
  • 102
  • 193
  • 3
    A NullReference is a runtime exception, not a compiler error. Are you sure you're describing the error correctly? And you need to provide more context - where is the code for your VM? Is this Label inside of an item template? – Jason May 14 '21 at 15:20
  • 1) `Colleciton[0]` - is that a typo? "Collection"? 2) Show more code - show enough so we can see exactly how "MyProperty" should be referenced. 3) Do some experiments to isolate exactly what is wrong. Are you able to bind to "MainObject"? To "MainObject.Colleciton[0]"? How about if you make a `property` in your viewmodel, something like `public MyType OneItem { get {return MainObject.Collectiton[0]; } }`, then refer to it as `"{Binding OneItem.MyProperty}"`? 4) If put a breakpoint on that `get {return ...` line, and examine variables there, is something `null`? – ToolmakerSteve May 14 '21 at 17:14
  • @ToolmakerSteve That's a bad suggestion, your property wouldn't trigger its update event if the collection received a new first element (either inserting a the beginning or removing the beginning). If you want to go that route, use OAPH or its equivalent in your framework. – Blindy May 14 '21 at 18:30
  • @Blindy - you are right; I should have clarified that was just a test to isolate what was wrong in their code. As Blindy says, DON'T use that code as-is in production code. XAML will have no way to know when the value changes. – ToolmakerSteve May 14 '21 at 18:52

1 Answers1

1

The odd thing is that the intellisense detect MyProperty

The property chain might be valid, but that doesn't mean all the parts have valid (ie, non-null) data. Specifically, indexing a collection is most likely not protected with null checks in Xamarin.

So, make sure you actually initialize your properties!

Blindy
  • 65,249
  • 10
  • 91
  • 131