c# - WPF,列表框中没有显示任何内容

标签 c# wpf xaml listbox itemssource

我不知道我在这里做错了什么。我有一个 ListBox,其 DataContextItemsSource 已设置,但是当我运行我的时 ListBox 中没有任何内容应用程序。调试时,我获取 ListBox 项的方法的第一行永远不会被命中。这是我拥有的:

// Constructor in UserControl
public TemplateList()
{
    _templates = new Templates();
    InitializeComponent();
    DataContext = this;
}

// ItemsSource of ListBox
public List<Template> GetTemplates()
{
    if (!tryReadTemplatesIfNecessary(ref _templates))
    {
        return new List<Template>
            {
                // Template with Name property set:
                new Template("No saved templates", null)
            };
    }
    return _templates.ToList();
}

这是我的 XAML:

<ListBox ItemsSource="{Binding Path=GetTemplates}" Grid.Row="1" Grid.Column="1"
         Width="400" Height="300" DisplayMemberPath="Name"
         SelectedValuePath="Name"/>

Template 类的一个实例上,有一个 Name 属性,它只是一个 string。我只想显示模板名称列表。用户不会更改 Template 中的任何数据,ListBox 只需要是只读的即可。

模板还有一个 Data 属性,稍后我将在这个 ListBox 中显示它,所以我不想让 GetTemplates 返回只是一个字符串列表——它需要返回一些 Template 对象的集合。

最佳答案

您不能绑定(bind)到方法。将其设为属性,它应该可以正常工作。

最好将 List 设置为 DataContext,或创建一个包含该列表的 ViewModel。这样一来,您将可以更好地控制列表框将绑定(bind)到的实例。

希望这对您有所帮助!

关于c# - WPF,列表框中没有显示任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3503399/

相关文章:

c# - c#中的表达式和委托(delegate)

WPF CollectionViewSource 多个 View ?

windows-phone-7 - Windows Phone 8 中的复选框行为类似于手机中的电子邮件

c# - WPF 中的文化更改后更新资源字符串(GUI 中的文本)

c# - 在父子关系中使用泛型

C# if 语句速记运算符 (?:) results in unreachable code

c# - WPF标签下的可点击按钮

c# - .NET MAUI 项目始终为空

c# - 如何从数据表中删除空行和多余的列

c# - 从sql数据库检索图像(字节数组)并显示图像