2010-11-15 86 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); 

    }