.net – WPF: Set Binding-property for ListBox-binding

bindinglistboxnetwpf

I have a listbox where I bind the ItemsSource to a collection stored in the set DataContext object. This makes the list displayed using the ToString() function.

<ListBox ItemsSource="{Binding SomeCollection}"></ListBox>                    

Now I want to display a property for the objects in the collection instead. So I want to define a template etc to do this on all the objects in the bound list. I tried a variety of different approaches without success. I'd like to do something like this:

<ListBox ItemsSource="{Binding SomeCollection}">
    <ListBox.Template>
        <ControlTemplate>                                
            <ListViewItem Content="{Binding ThePropertyOnElm}"></ListViewItem>
        </ControlTemplate>
    </ListBox.Template>
</ListBox>

Can anyone help me make this right?

Best Answer

you don't need to specify a template, you can just use the DisplayMemberPath property, like so:

<ListBox ItemsSource="{Binding SomeCollection}" DisplayMemberPath="ThePropertyOnElm" />

hope this helps!