Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF: Set Binding-property for ListBox-binding

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?

like image 530
stiank81 Avatar asked Sep 16 '09 12:09

stiank81


2 Answers

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!

like image 152
RoelF Avatar answered Oct 24 '22 01:10

RoelF


I think this is what youre wanting to do:

<ListBox ItemsSource="{Binding SomeCollection}">
    <ListBox.ItemTemplate>
        <DataTemplate DataType="{x:Type local:YourDataType}">                                
            <TextBlock Text="{Binding ThePropertyOnElm}" />
        </ControlTemplate>
    </ListBox.ItemTemplate>
</ListBox>

The Template for the ListBox is going to modify how the actual listbox looks, and itemtemplate is going to control how the individual items in the listbox will look. I changed the controltemplate into a DataTemplate and assigned it to the type of YourDataType. Also, I used a textblock within the data template instead of listboxitem since the datatemplate is being assigned to the listboxitem (which should contain some type of content instead of another listboxitem).

i havent tried compiling this so it might not be exactly correct. if it doesnt let me know and ill take the extra steps!

like image 23
Mark Synowiec Avatar answered Oct 23 '22 23:10

Mark Synowiec