C# 将自定义对象数据显示到 ListBox WPF

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/576515/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 08:55:38  来源:igfitidea点击:

Display custom object data to ListBox WPF

c#wpf

提问by Sachin Gaur

I have a ListBox in WPF application as :

我在 WPF 应用程序中有一个 ListBox 为:

<ListBox HorizontalAlignment="Left" Margin="16,37,0,16" Name="lbEmpList" Width="194" SelectionChanged="lbEmpList_SelectionChanged" FontSize="12" SelectionMode="Single">

</ListBox>

I have three buttons: Add, Remove and Update that will add, remove and update items to the list box. I am adding Items to the ListBox my custom class object names objEmployee. This custom class contains few properties: Id, Name, Address.
But, when I add the object to ListBox, then it will display items as

我有三个按钮:添加、删除和更新,它们将向列表框中添加、删除和更新项目。我正在将 Items 添加到我的自定义类对象名称objEmployee的 ListBox 中。这个自定义类包含几个属性:Id、Name、Address。
但是,当我将对象添加到 ListBox 时,它会将项目显示为

<Namespace Name>.<Custom Object name>

How can I bind any of the object property to this ListBox at Design or run time to acheive my functionality?

如何在设计或运行时将任何对象属性绑定到此 ListBox 以实现我的功能?

采纳答案by Matt Hamilton

Couple of options:

几个选项:

The first, easiest option is to set the ListBox's DisplayMemberPathproperty to a property of your custom object. So if your Employee class has a LastName property you could do this:

第一个最简单的选项是将 ListBox 的DisplayMemberPath属性设置为自定义对象的属性。因此,如果您的 Employee 类具有 LastName 属性,您可以这样做:

<ListBox DisplayMemberPath="LastName" ... />

If you want more control over the data that's displayed for each item (including custom layout etc) then you'll want to define a DataTemplatefor each item in your ListBox. The easiest way to do this is by simply setting the ListBox's ItemTemplateproperty:

如果您想更好地控制为每个项目(包括自定义布局等)显示的数据,那么您需要为ListBox 中的每个项目定义一个DataTemplate。最简单的方法是简单地设置 ListBox 的ItemTemplate属性:

<ListBox ...>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <TextBlock Text="{Binding FirstName}" />
                <TextBlock Text="{Binding LastName}" />
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Have a read through the links I've provided and check out some of the example code on MSDN.

通读我提供的链接并查看 MSDN 上的一些示例代码。