Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get clicked element from ListBox in WPF

I have a listbox with a datatemplate

<Button Name="ButtonSortDate" Content="Date" Grid.Column="1" Click="ButtonSortDateClick" />
<Button Name="ButtonSortABC" Content="ABC.." Grid.Column="2" Click="ButtonSortABCClick" />
<!--ItemsSource="{Binding NotesCollection}"-->
<ListBox Name="ListBoxNotes" 
    Grid.Row="1" Grid.ColumnSpan="3"                             
    DoubleTap="DeleteDoubleTap">
    <ListBox.ItemTemplate>                            
        <DataTemplate>
            <StackPanel Margin="0,0,0,17" Width="432" Height="78" >
                <TextBlock Text="{Binding NoteText}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}" />
                <TextBlock Text="{Binding Date}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

I want to be able to dobble tap an item in the List to delete it, but I cant find any way to get the clicked item, only the selected (Which is not always the same)

If I for example tap Item 1 in the list and dobble taps the second, then the ListBox.SelectedItem will be the first Item.

How do I get Item 2? Would be nice if I could put an event on the item itself somehow in the template

like image 844
Mech0z Avatar asked Oct 22 '25 04:10

Mech0z


1 Answers

The e.OriginalSource should be some element within the item (e.g. one of the TextBlocks), it has the item as DataContext, so you should be able to remove the item from your source collection like this:

var item = (FrameworkElement)e.OriginalSource;
Data.Remove((MyItemType)item.DataContext);
like image 196
H.B. Avatar answered Oct 23 '25 19:10

H.B.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!