我不知道我在做什麼錯在這裏。我有一個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