Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

silverlight/windows phone 7 selectedIndex problems with button inside listbox

I've got a listbox with a simple list of items. On my xaml page, I have the following

<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>

In my codebehind, I try to grab the selectedIndex so I can remove the item from the collection that is bound to my listbox.

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);

        }

However, no matter on which row I click the delete button, selectedIndex is always -1

what am I missing?

thanks in advance!

like image 312
Dave Avatar asked Nov 15 '10 03:11

Dave


1 Answers

You can do what you want by setting the Tag property of the button to your object like this:

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

Then in the eventhandler you can do this:

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

Not sure what your Person object is called so I didn't cast the Tag to it, but you will probably have to do that, but looks like you are comfortable with that.


Is there a missing StackPanel start element in your XAML? This is probably just an oversight, but could cause you some problems if this is your actual code.

like image 59
theChrisKent Avatar answered Oct 05 '22 02:10

theChrisKent