c# - 未找到列表框 DisplayMemberPath 属性

标签 c# wpf xaml listbox

在 WPF 项目中使用 Microsoft Visual Studio。我有一个 ListBox,它的 ItemsSource 被设置为一个名为 LuhFile 的对象列表。 LuhFile 包含一个公共(public)字符串 displayName。我希望列表框显示 displayName,但是当我将 displayname 设置为 ListBox 的 displayMemberPath 时,出现此错误:

System.Windows.Data Error: 40 : BindingExpression path error: 'displayName' property not found on 'object' ''LuhFile' (HashCode=61470144)'. BindingExpression:Path=displayName; DataItem='LuhFile' (HashCode=61470144); target element is 'TextBlock' (Name=''); target property is 'Text' (type 'String')

c#主窗口

    private List<LuhFile> luhFileList;

    public MainWindow()
    {
        InitializeComponent();
        luhFileList = new List<LuhFile>();
        luhFileList.Add(new LuhFile("testPath", "testName", "testDisplay"));
        luhListBox.ItemsSource = luhFileList;
    }

c# LuhFile

class LuhFile
{
    public string path;
    public string fileName;
    public string displayName;

    public LuhFile(string givenPath, string givenFileName, string givenDisplayName)
    {
        path = givenPath;
        fileName = givenFileName;
        displayName = givenDisplayName;
    }
}

XAML

<ListBox x:Name="luhListBox" MinHeight="100" MaxHeight="130" DisplayMemberPath="displayName" />

最佳答案

WPF 中的数据绑定(bind)适用于公共(public)属性,而不适用于字段。

因此将您的项目类别更改为:

public class LuhFile
{
    public string path { get; set; }
    public string fileName { get; set; }
    public string displayName { get; set; }
    ...
}

关于c# - 未找到列表框 DisplayMemberPath 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37618622/

相关文章:

c# - vs2008 c# : Facebook. rest.api 如何使用它获取好友列表?

c# - WPF donut 进度条

C# WPF Windows 10 (1803) TouchKeyboard 不可靠问题 (Prism ClickOnce)

c# - 如何在不卡住 WPF 应用程序中的 UI 线程的情况下让子线程休眠?

c# - ItemsControl 和 Canvas 中的多个数据模板

c# - 我们可以在不使用 IEnumerable 接口(interface)的情况下使用 GetEnumerator() 吗?

c# - 为什么远程调试对 IIS 托管的 WCF 服务不起作用?

c# - 如何为多对多映射配置 nHibernate?

c# - 过滤 ObservableCollection?

c# - 如何在 C#/XAML windows 8 应用程序中预选多个 ListView / GridView 项目?