Libor Zapletal
Libor Zapletal

Reputation: 14102

WP7 Delete item from listbox

I have this listbox in my page:

<ListBox x:Name="lstData" Tap="lstData_Tap" ItemsSource="{Binding 
                             Source={StaticResource favoriteAddressCollection}, 
                             Path=DataCollection}" Margin="22">
            <ListBox.ItemTemplate >
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <Image Source="/Images/Search/favorite_red.png" Margin="12" />
                        <TextBlock Text="{Binding Path=Address}" VerticalAlignment="Center" Width="300" />
                        <Button BorderThickness="0"  Width="60" Height="60" HorizontalAlignment="Right"
                                Tap="imgDelete_Tap">
                            <Button.Background>
                                <ImageBrush ImageSource="/Images/Search/unfavorite.png"></ImageBrush>
                            </Button.Background>
                        </Button>
                        <!--<Image x:Name="imgDelete" Source="/Images/Search/unfavorite.png" Width="40" Margin="12" HorizontalAlignment="Right"
                               Tap="imgDelete_Tap" />-->
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

Now I want to delete item after clicking on that image. I don't have set SelectedItem or SelectedIndex so how can I other way delete item? How can I find out on which line I clicked on image?

Upvotes: 0

Views: 284

Answers (2)

Haspemulator
Haspemulator

Reputation: 11308

First, I'm not recommending using Tap event on the button. There's Click event for this purpose. Second, related to your question: in your event handler (it could be Tap or Click, doesn't matter) you write code like this:

Button btn = sender as Button;
YourViewModelDataType itemContext = btn.DataContext as YourViewModelDataType;

And then in itemContext variable you have a reference to the item that needs to be deleted from the favorites collection, or do whatever you want to do with it.

Upvotes: 1

Raxr
Raxr

Reputation: 985

You should bind the SelectedItem as argument/parameter of that buttons command. Then you can bind that buttons command to a method in your viewmodel, where the selected item is automatically passed as an argument.

Upvotes: 0

Related Questions