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

ItemsControl的DisplayMemberPath属性失效,如何正确显示Name属性?

解决ItemsControl绑定后Expander内容为空的问题

排查方向与解决方案

1. 确认数据源有效性

  • 先验证attributes集合是否包含数据:添加调试代码Debug.WriteLine($"属性总数:{attributes.Count}");,如果输出为0,说明_dataProvider.GetSchemaAttributes()未返回有效数据,需先排查数据提供逻辑。
  • 若后续需要支持数据更新通知,建议将attributes改为ObservableCollection<SchemaAttribute>类型;如果仅需初始显示,普通List<SchemaAttribute>也可,但要确保集合本身非空。

2. 检查SchemaAttribute的Name属性定义

确保Name是公共可读取的属性,绑定无法访问私有/保护成员或仅写属性:

public class SchemaAttribute
{
    public string Name { get; set; } // 必须是公共、带get访问器的属性
    // 其他属性...
}

3. 用ItemTemplate替代DisplayMemberPath(更可靠的显示方式)

如果DisplayMemberPath不生效,直接定义ItemTemplate可明确控制显示逻辑:

ItemsControl itemsControl = new ItemsControl();
itemsControl.ItemsSource = attributes;

// 手动创建数据模板,绑定Name属性到TextBlock
itemsControl.ItemTemplate = new DataTemplate(typeof(SchemaAttribute))
{
    VisualTree = new FrameworkElementFactory(typeof(TextBlock))
    {
        Bindings = { new Binding("Name") }
    }
};

expander.Content = itemsControl;

4. 确保Expander已加入可视化树

如果Expander没有被添加到窗口或容器的子元素集合中,即便内部有内容也不会显示。例如将其添加到Grid容器:

// 假设存在名为mainGrid的Grid容器
mainGrid.Children.Add(expander);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 15:35:12