You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WPF如何将ObservableCollection中类的name属性绑定到ListView

实现方式

你可以选择以下任意一种方法完成需求:

  • 方法1:直接设置DisplayMemberPath属性
    这是最简便的实现,仅需在原有ListView代码上新增DisplayMemberPath属性,指定要展示的Robot类的name字段即可:
<ListView ItemsSource="{Binding Robots}" DisplayMemberPath="name" />
  • 方法2:自定义ItemTemplate数据模板
    如果后续需要扩展列表项的布局(比如新增图标、操作按钮等),可以通过自定义数据模板实现:
<ListView ItemsSource="{Binding Robots}">
    <ListView.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding name}" />
            <!-- 可在此处添加其他控件扩展布局 -->
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>
  • 方法3:重写Robot类的ToString()方法
    WPF列表控件未指定展示字段时,默认会调用数据项的ToString()方法渲染内容,你可以重写该方法返回名称,无需修改原有XAML代码:
public class Robot
{
    public string name { get; private set; }

    public Robot(string robotName)
    {
        name = robotName;
    }

    public override string ToString()
    {
        return name;
    }
}

内容的提问来源于stack exchange,提问作者Alive318

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 11:48:00