silverlight/windows phone 7 selectedIndex列表框内按钮的问题

Dav*_*ave 5 silverlight listbox windows-phone-7

我有一个包含简单项目列表的列表框.在我的xaml页面上,我有以下内容

<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>
Run Code Online (Sandbox Code Playgroud)

在我的代码隐藏中,我尝试抓取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);

        }
Run Code Online (Sandbox Code Playgroud)

但是,无论我在哪一行单击删除按钮,selectedIndex始终为-1

我错过了什么?

提前致谢!

the*_*ent 6

您可以通过将按钮的Tag属性设置为对象来执行您想要的操作,如下所示:

<Button BorderThickness="0" Click="buttonPerson_Click" Tag="{Binding BindsDirectlyToSource=True}">
     <Image Source="delete-icon.png"/>
</Button>
Run Code Online (Sandbox Code Playgroud)

然后在事件处理程序中,您可以这样做:

private void buttonPerson_Click(object sender, RoutedEventArgs e)
{
    myPersonList.remove((sender as Button).Tag);
}
Run Code Online (Sandbox Code Playgroud)

不确定你的Person对象被调用了什么,所以我没有将Tag转换为它,但你可能不得不这样做,但看起来你对此感到满意.


XAML中是否缺少StackPanel启动元素?这可能只是一个疏忽,但如果这是您的实际代码,可能会导致一些问题.