Silverlight / windows phone 7 selectedIndex problems with a button inside the list

I have a list 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 code, I am trying to grab selectedIndex so that I can remove an item from the collection bound to my list.

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 which line I click on the delete button, selectedIndex is always -1

What am I missing?

early!

+5
source share
4 answers

You can do what you want by setting the button tag property on your object as follows:

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

Then in the event handler you can do this:

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

, Person, , , , , , .


XAML StackPanel? , , , .

+6

, , DataContext , , List Remove. - : -

 ((IList)myPersonList).Remove(((Button)sender).DataContext);
+2

touch (click), .

SelectedIndex , , . ( , sender, .)

+1

I know you have the answer, but this is another way to do what you ask. You can also use the selecteditem property

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

    }
+1
source

All Articles