我不知道我在这里做错了什么。我有一个 ListBox
,其 DataContext
和 ItemsSource
已设置,但是当我运行我的时 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/