我不知道我在做什么错在这里。我有一个ListBox
其DataContext
和ItemsSource
设置,但是当我运行我的应用程序时ListBox
没有任何内容。在调试时,我的获取ListBox
物品的方法的第一行永远不会被击中。下面是我有:WPF,什么也没有显示在列表框中
// 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
对象的一些集合。
这是干净多了!我将我的'GetTemplates'方法设置为private,并在构造函数中设置'DataContext = GetTemplates()'。然后,我只是将我的XAML中的ItemsSource设置为我的'Templates'类已有的'List'属性 - 谢谢! – 2010-08-17 14:31:48
很高兴我可以帮忙;) – Arcturus 2010-08-17 14:41:46
顺便说一句,如果你真的想从Xaml调用一个方法,看看ObjectDataProvider。 Bea Stollnitz有一个不错的博客: http://bea.stollnitz.com/blog/?p=22 – Arcturus 2010-08-17 14:43:20