2010-09-13 97 views
0

我有下面的代碼WPF,的ObservableCollection和列表框

private static ObservableCollection<myColor> myItems = new ObservableCollection<myColor>(); 
myItems.Add(new myColor("red")); 

當對象myColor是該類

public class myColor 
{ 
    public string color { get; set; } 
    public myColor(string col) 
    { 
     this.color = col; 
    } 
} 

麻煩的是,當我嘗試在列表框中顯示的項目

<ListBox Margin="12,52,12,12" Name="listBox1" ItemsSource="{Binding}" /> 

它只顯示「myColor」對象而不是「顏色」變量。我怎樣才能顯示這個對象的變量?

回答

0

如果您只想在列表框中顯示項目的字符串屬性DisplayMemberPath

否則使用ItemTemplate,您可以將它設置爲DataTemplate,該DataTemplate定義每個項目的外觀和可能具有任何複雜性(即可以包含其他控件)的方式。

0

首先設置的DataContext爲窗口,如下圖所示:

 public Window1() 
     { 
      InitializeComponent(); 

      myItems.Add(new myColor("red")); 
      myItems.Add(new myColor("green")); 

      //Set the DataContext for the window 
      this.DataContext = myItems; 
     } 

現在改變XAML到:

<ListBox Margin="12,52,12,12" Name="listBox1" ItemsSource="{Binding}" DisplayMemberPath="color" /> 

這就是全部。它應該解決你的問題。