Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom WPF ListBox using c#

Tags:

c#

wpf

xaml

listbox

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.

like image 920
tweetysat Avatar asked Jan 29 '26 13:01

tweetysat


1 Answers

  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

like image 194
H.B. Avatar answered Feb 01 '26 02:02

H.B.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!