Search code examples
c#wpfmvvmcomboboxbinding

WPF MVVM: Binding to property of object


I try to display values in my ComboBox using Binding. But I have no idea why isn't it working:

<ComboBox Width="476" Height="30" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="10,10,0,0" ItemsSource="{Binding Maps.Name}"></ComboBox>

Here is my C#:

public class Map
{
    public string Name { get; set; }
    public string ImagePath { get; set; }
}

And main:

class MainWindowViewModel : BindableBase
{
    public ObservableCollection<Map> Maps { get; set; }

    public MainWindowViewModel()
    {
        Maps = mainWindowModel.LoadMapFiles(); //deserializes maps, i checked it, LoadMapFiles() works
    }
}

What should I write in ComboBox ItemSource if I want it to display every Map.Name?


Solution

  • The expression Maps.Name is not a valid Binding Path, because Name is not a property of the ObservableCollection<Map> in Maps.

    Bind the ItemsSource property to the collection property, and set the displayed property by DisplayMemberPath:

    <ComboBox ItemsSource="{Binding Maps}" DisplayMemberPath="Name" ... />
    

    Also make sure that the Maps property setter fires a change notification, or make the property read-only:

    public ObservableCollection<Map> Maps { get; }