Search code examples
xamarin.formsdata-bindingmaui

.NET MAUI Binding Path and Source in the MVVM Pattern


I have a List<Foo> FooList that resides in my ViewModel & I have a Models folder detailing the Foo object with its properties (FooName, FooTime, etc). I need my Picker's ItemSource to be bound to FooList but I need ItemDisplayBinding to be bound to Foo.FooName. Despite reading all the binding documentation and trying many combinations I can't get it to work.

For example, I've tried to avail:

ItemsSource="{Binding FooList}"
ItemDisplayBinding="{Binding Source={models:Foo}, Path=FooName}"

In a CollectionView, it's easy enough to render elements with Foo.FooName via the DataTemplate, but a Picker doesn't have that property. I'd really appreciate some guidance, as I've long wondered how to use the Source/Path properties for more than x:References to XAML-defined x:Names.


Solution

  • As Jason said that you can "{Binding FooName}" directly. And you can refer to the official doc: Populate a Picker with data using data binding:

    When binding to a list of objects, the Picker must be told which property to display from each object. This is achieved by setting the ItemDisplayBinding property to the required property from each object. In the code examples above, the Picker is set to display each Monkey.Name property value.

    In addition, you said that it's easy for CollectionView to do same thing with the help of DataTemplate. You can see this: Create a DataTemplate:

    A DataTemplate is used to specify the appearance of data, and typically uses data binding to display data. A common usage scenario for data templates is when displaying data from a collection of objects in a control such as a CollectionView or CarouselView. For example, when a CollectionView is bound to a collection of Person objects, the CollectionView.ItemTemplate property can be set to a DataTemplate that defines the appearance of each Person object in the CollectionView. The DataTemplate will contain objects that bind to property values of each Person object.

    About Source/Path of Binding, you can check the official doc: Binding path, it's very good and detailed.