简体   繁体   中英

Custom WPF ListBox using c#

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. You should assign an ItemTemplate to the ListBox which binds to properties on the items. eg

     <ListBox.ItemTemplate> <DataTemplate> <StackPanel> <TextBlock Text="{Binding Id}"/> <!-- ... --> 
  2. You add items which have those properties, eg anonymous objects :

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

See also: Data Templating

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