2014-03-31 24 views
3

我正在嘗試設置一個列表框,用戶可以通過單擊要刪除的每個值來刪除項目。 我設置樣式爲我列表框(顯示名稱是項目類的成員)在orderto包括每個項目的按鈕:帶自動刪除項目的WPF列表框

<ListBox.ItemTemplate> 
     <DataTemplate> 
      <StackPanel Orientation="Horizontal"> 
       <TextBlock Text="{Binding DisplayName}" /> 
       <Button Content="[x]" /> 
      </StackPanel> 
     </DataTemplate> 
    </ListBox.ItemTemplate> 

現在我有麻煩試圖設置按鈕刪除相關條目。 有人可以指路嗎? 預先感謝您。

+0

顯示列表框結合,並得到 – Paparazzi

回答

3

我建議您使用ICommand並通過命令參數傳遞列表框的選定項目。

<ListBox x:Name="MyListBoxName"> 
     <ListBox.ItemTemplate> 
     <DataTemplate> 
      <StackPanel Orientation="Horizontal"> 
      <TextBlock Text="{Binding DisplayName}" /> 
      <Button Content="[x]" 
        Command="{Binding ElementName=MyListBoxName, Path=DataContext.DeleteItemCommand}" 
        CommandParameter="{Binding }" /> 
      </StackPanel> 
     </DataTemplate> 
     </ListBox.ItemTemplate> 
    </ListBox> 

public class YourViewModel 
    { 
     public ICommand DeleteItemCommand { get; set; } 
     public ObservableCollection<SomeClass> ListBoxDataSource { get; set; } 

     public YourViewModel() 
     { 
      DeleteItemCommand = new DelegateCommand<object>(DeleteItem); 
     } 

     private void DeleteItem(object item) 
     { 

     } 
    } 
+1

關閉,但您的綁定是有點過。 「ListBoxItem」的'DataContext'將是集合中的一個項目,因此您需要使用'RelativeSource'或'ElementName'綁定來查找'ListBox.DataContext'並獲取DeleteCommand。這比爲列表中的每個項目添加「DeleteCommand」更實用。我希望你不介意,但我正在調整你的代碼示例來顯示這個:) – Rachel

+0

是的你的權利。我忘記了參考層次。 – TMan

+0

順便說一下,如果你還記得我,但你很早以前回答我的問題時,我仍然是絕望的新秀,希望學習。讓我告訴你我從那以後就採用了LONNNGG方式。 :)你有助於爲我奠定基礎,併爲我付出了很大的時間。感謝您的幫助,並幫助其他人解決堆棧溢出問題。 http://stackoverflow.com/questions/7905920/making-a-customized-schedule-in-wpf – TMan