2010-08-17 48 views
1

我不知道我在做什麼錯在這裏。我有一個ListBoxDataContextItemsSource設置,但是當我運行我的應用程序時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對象的一些集合。

回答

6

您無法綁定到方法。使它成爲一個財產,它應該工作。

儘管將List設置爲DataContext,或者創建了一個包含列表的ViewModel,但它更好。 Thay的方式,你將更好地控制你的Listbox綁定到的實例。

希望這會有所幫助!

+1

這是乾淨多了!我將我的'GetTemplates'方法設置爲private,並在構造函數中設置'DataContext = GetTemplates()'。然後,我只是將我的XAML中的ItemsSource設置爲我的'Templates'類已有的'List'屬性 - 謝謝! – 2010-08-17 14:31:48

+1

很高興我可以幫忙;) – Arcturus 2010-08-17 14:41:46

+1

順便說一句,如果你真的想從Xaml調用一個方法,看看ObjectDataProvider。 Bea Stollnitz有一個不錯的博客: http://bea.stollnitz.com/blog/?p=22 – Arcturus 2010-08-17 14:43:20

1

當您應該使用屬性時,您正嘗試在綁定中調用方法。將它改爲一個屬性,你應該很好去。

public List<Template> MyTemplates {get; private set;} 

public TemplateList() 
{ 
    InitializeComponent(); 
    SetTemplates(); 
    DataContext = this; 
} 

// ItemsSource of ListBox 
public void SetTemplates() 
{ 
    // do stuff to set up the MyTemplates proeprty 
    MyTemplates = something.ToList(); 
} 

的XAML:

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