简体   繁体   中英

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?

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; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM