Reputation: 2403
First step : a simple ListBox
<ListBox Height="95" HorizontalAlignment="Left" Margin="17,0,0,0" Name="myList" VerticalAlignment="Top" Width="287">
with that code :
myList.Items.Add("toto");
Ok, it's working fine.
Second step : I want to have two columns for each row.
So I tried that
<ListBoxItem Name="my_item">
<StackPanel Orientation="Horizontal">
<TextBlock Name="my_item_id"></TextBlock>
<TextBlock Name="my_item_name"></TextBlock>
</StackPanel>
</ListBoxItem>
But in my code ?
I tried
my_item_id = "1234";
my_item_name = "toto";
myList.Items.Add(my_item);
But it's not working ... I suppose I'm doing wrong but then how to make it working ?
Thanks.
Upvotes: 3
Views: 2460
Reputation: 184326
You should assign an ItemTemplate
to the ListBox
which binds to properties on the items. e.g.
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Id}"/>
<!-- ... -->
You add items which have those properties, e.g. anonymous objects:
myList.Items.Add(new { Id = "Lorem", ... });
See also: Data Templating
Upvotes: 7