3

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.

1
  • In case you want the columns to be resizable and have a more Grid-Like look and feel think about using a ListView instead of ListBox Commented Feb 13, 2012 at 17:41

1 Answer 1

7
  1. 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}"/>
                <!-- ... -->
    
  2. You add items which have those properties, e.g. anonymous objects:

    myList.Items.Add(new { Id = "Lorem", ... });
    

See also: Data Templating

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.