2010-11-15 71 views
5

我有一個列表框中的一個簡單的項目列表。在我的XAML頁面,我有以下silverlight/windows phone 7 selectedIndex問題列表框中的按鈕

<ListBox Name="listBox1"> 
         <ListBox.ItemTemplate> 
          <DataTemplate> 
            <TextBlock Text="{Binding firstName}"/> 
            <TextBlock Text="{Binding lastName}"/> 
            <Button BorderThickness="0" Click="buttonPerson_Click"> 
             <Image Source="delete-icon.png"/> 
            </Button> 
           </StackPanel> 
          </DataTemplate> 
         </ListBox.ItemTemplate> 
        </ListBox> 

在我隱藏,我試圖抓住將selectedIndex,所以我可以從綁定到我的列表框集合中刪除的項目。

private void buttonPerson_Click(object sender, RoutedEventArgs e) 
     { 

      // If selected index is -1 (no selection) do nothing 
      if (listBox1.SelectedIndex == -1) 
       return; 

      myPersonList.removeAt(listBox1.SelectedIndex); 

     } 

然而,無論在哪一行我點擊刪除按鈕,的selectedIndex始終是-1

我缺少什麼?

在此先感謝!

回答

6

你可以做你想做的通過按鈕的Tag屬性這樣的設置到對象:在事件處理程序然後

<Button BorderThickness="0" Click="buttonPerson_Click" Tag="{Binding BindsDirectlyToSource=True}"> 
    <Image Source="delete-icon.png"/> 
</Button> 

你可以這樣做:

private void buttonPerson_Click(object sender, RoutedEventArgs e) 
{ 
    myPersonList.remove((sender as Button).Tag); 
} 

不知道你的Person對象被稱爲所以我沒有標籤投給它,但你可能要做到這一點,但看起來,你是舒服。


在您的XAML中是否存在缺少StackPanel啓動元素?這可能只是一個疏忽,但如果這是您的實際代碼,可能會導致一些問題。

+0

這個答案已經相當有幫助的。如果我不想將整個對象附加到標籤怎麼辦?如果我只是想附加一個數字..說... selectedIndex? – Dave 2010-11-16 08:57:54

+1

我會避免使用索引(因爲它更難做,而且代碼更改時靈活性更低)。您可以添加一個ID屬性(獨特的東西)到您的自定義對象,並將標籤綁定到此。然後,您可以循環訪問列表並根據此ID刪除,或者使用密鑰設置爲該ID的字典。 – theChrisKent 2010-11-16 14:20:56

1

該按鈕正在捕獲觸摸(單擊)事件,因此該項目永遠不會被選中。

而不是使用SelectedIndex,你應該找出哪個項目刪除基於哪個按鈕被點擊。 (通過看sender傳遞給事件處理程序執行此操作。)

2

將發件人的按鈕,點擊過,其DataContext將要刪除的項目和典型的List實施將有一個Remove方法。所以像這樣的在一般情況下工作: -

((IList)myPersonList).Remove(((Button)sender).DataContext); 
1

我知道你有一個答案,但這是另一種方式來做你所要求的。 你也可以使用SelectedItem屬性

private void buttonPerson_Click(object sender, RoutedEventArgs e) 
{ 

     // Select the item in the listbox that was clicked 
     listBox1.SelectedItem = ((Button)sender).DataContext; 

     // If selected index is -1 (no selection) do nothing 
     if (listBox1.SelectedItem == null) 
      return; 

     // Cast you bound list datatype. 
     myPersonList.remove(([myPersonList Type])listBox1.SelectedValue); 

    }