2017-04-13 51 views
0

我試圖使用列表框來選擇一個條目,然後顯示屬於此選定條目的圖片。但就在一開始,我得到了第一個問題:用綁定填充ListBox正在工作,但如果我在正在運行的程序中單擊一行,它不會選擇該行。我只能看到突出顯示的懸停效果,但不能選擇一行。任何想法我的錯誤可能是什麼?充滿綁定的列表框不會選擇單擊項目

這是我的XAML:

 <ListBox x:Name="entrySelection" ItemsSource="{Binding Path=entryItems}" HorizontalAlignment="Left" Height="335" Margin="428,349,0,0" VerticalAlignment="Top" Width="540" FontSize="24"/> 

而在MainWindow.xaml.cs我填充條目列表框:

private void fillEntrySelectionListBox() 
    { 
     //Fill listBox with entries for active user 
     DataContext = this; 
     entryItems = new ObservableCollection<ComboBoxItem>(); 
     foreach (HistoryEntry h in activeUser.History) 
     { 
      var cbItem = new ComboBoxItem(); 
      cbItem.Content = h.toString(); 
      entryItems.Add(cbItem); 
     } 
     this.entrySelection.ItemsSource = entryItems; 
     labelEntrySelection.Text = "Einträge für: " + activeUser.Id; 

     //show image matching the selected entry 
     if (activeUser.History != null) 
     { 
      int index = entrySelection.SelectedIndex; 
      if (index != -1 && index < activeUser.History.Count) 
      { 
       this.entryImage.Source = activeUser.History[index].Image; 
      } 
     } 
    } 

所以我可以看到我的列表框填寫正確,但不選擇任何東西 - 所以我不能繼續加載匹配所選條目的圖片。 我還是很新的節目,所以任何幫助將是巨大的:)


編輯:如果有人需要看看這個線程後:這裏的 - 很明顯 - 溶液

現在XAML看起來是這樣的

<ListBox x:Name="entrySelection" ItemsSource="{Binding Path=entryItems}" HorizontalAlignment="Left" Height="335" Margin="428,349,0,0" VerticalAlignment="Top" Width="540" FontFamily="Siemens sans" FontSize="24"> 
     <ListBox.ItemTemplate> 
      <DataTemplate> 
       <TextBlock Text="{Binding Text}"/> 
      </DataTemplate> 
     </ListBox.ItemTemplate> 
    </ListBox> 

後面的代碼填充它:

//Fill listbox with entries for selected user 
DataContext = this; 
entryItems = new ObservableCollection<DataItem>(); 
foreach (HistoryEntry h in selectedUser.History) 
{ 
    var lbItem = new DataItem(h.toString()); 
    entryItems.Add(lbItem); 
} 
this.entrySelection.ItemsSource = entryItems; 
labelEntrySelection.Text = "Einträge für: " + selectedUser.Id; 

和新的類DataItem:

class DataItem 
{ 
    private String text; 

    public DataItem(String s) 
    { 
     text = s; 
    } 

    public String Text 
    { 
     get 
     { 
      return text; 
     } 
    } 
} 

回答

0

您正在填充它與ComboBoxItem,這是與ListBox不相關,也是錯誤的定義。

您需要讓ObservableCollection充滿數據項。

意思是說,創建一個包含要存儲數據的類,而ListBox將爲每個數據項自動生成一個ListBoxItem。

http://www.wpf-tutorial.com/list-controls/listbox-control/

+0

哦,感謝這暗示 - 這是一個複製和粘貼錯誤。我會嘗試:) – Denise

+0

是的,現在它的工作原理 - 我現在感覺很蠢^^謝謝你的幫助:) – Denise

相關問題