2013-02-18 91 views
0

刪除項目我有這個列表框在我的網頁:WP7從列表框中

<ListBox x:Name="lstData" Tap="lstData_Tap" ItemsSource="{Binding 
          Source={StaticResource favoriteAddressCollection}, 
          Path=DataCollection}" Margin="22"> 
      <ListBox.ItemTemplate > 
       <DataTemplate> 
        <StackPanel Orientation="Horizontal"> 
         <Image Source="/Images/Search/favorite_red.png" Margin="12" /> 
         <TextBlock Text="{Binding Path=Address}" VerticalAlignment="Center" Width="300" /> 
         <Button BorderThickness="0" Width="60" Height="60" HorizontalAlignment="Right" 
           Tap="imgDelete_Tap"> 
          <Button.Background> 
           <ImageBrush ImageSource="/Images/Search/unfavorite.png"></ImageBrush> 
          </Button.Background> 
         </Button> 
         <!--<Image x:Name="imgDelete" Source="/Images/Search/unfavorite.png" Width="40" Margin="12" HorizontalAlignment="Right" 
           Tap="imgDelete_Tap" />--> 
        </StackPanel> 
       </DataTemplate> 
      </ListBox.ItemTemplate> 
     </ListBox> 

現在我想點擊該圖像後刪除項目。我沒有設置SelectedItem或SelectedIndex,所以我怎樣才能以其他方式刪除項目?如何找出我點擊圖像的哪一行?

回答

1

首先,我不推薦在按鈕上使用Tap事件。有Click事件用於此目的。 其次,涉及到你的問題:在你的事件處理程序(也可能是點擊或單擊,無所謂),你寫這樣的代碼:

Button btn = sender as Button; 
YourViewModelDataType itemContext = btn.DataContext as YourViewModelDataType; 

然後在itemContext變量,你必須對項目的引用需要從收藏集中刪除,或者做任何你想做的事情。

+0

這正是我所期待的。謝謝 – 2013-02-18 12:35:51

0

您應該將SelectedItem綁定爲該按鈕命令的參數/參數。然後,您可以將該按鈕命令綁定到viewmodel中的一個方法,其中所選項目作爲參數自動傳遞。

+0

它可以幫助,但我不知道如何綁定SelectedItem,我想這樣的事情:'CommandParameter =「{Binding SelectedItem}」'但它不工作。 – 2013-02-18 11:00:04

+0

嘗試{Binding ElementName = lstData,Path = SelectedItem}或者您可以Google一個wpf作爲相對綁定的cheatsheet。 – Raxr 2013-02-18 11:08:39