使用c#实现自定义WPF ListBox

3
第一步:一个简单的ListBox
<ListBox Height="95" HorizontalAlignment="Left" Margin="17,0,0,0" Name="myList" VerticalAlignment="Top" Width="287">

使用该代码:
myList.Items.Add("toto");

好的,它正常工作。

第二步:我希望每行有两栏。

所以我尝试了这个。

<ListBoxItem Name="my_item">
    <StackPanel Orientation="Horizontal">
        <TextBlock Name="my_item_id"></TextBlock>
        <TextBlock Name="my_item_name"></TextBlock>
    </StackPanel>
</ListBoxItem>

但是在我的代码中呢?
我尝试过。
my_item_id = "1234";
my_item_name = "toto";
myList.Items.Add(my_item);

但是它没有起作用...我想我做错了什么,那么如何使其起作用呢?

谢谢。


如果您希望列可以调整大小,并具有更类似网格的外观和感觉,请考虑使用ListView而不是ListBox。 - SvenG
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", ... });
    
请参见:数据模板

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接