简体   繁体   中英

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM