Monday, June 9, 2014

Find listbox item after tap and hold

First, make sure to put your gesture listener not under the ListBox itself, but in the top level container of the ListBox's data template (the StackPanel in this example):


<ListBox>  
    <ListBox.ItemTemplate>  
        <DataTemplate>   
            <StackPanel>   
                <toolkit:GestureService.GestureListener>   
                    <toolkit:GestureListener Hold="ListItem_Hold"/>   
                </toolkit:GestureService.GestureListener>   
                <TextBlock Text="{Binding LineOne}"/>   
                <TextBlock Text="{Binding LineTwo}"/>   
            </StackPanel>   
        </DataTemplate>  
    </ListBox.ItemTemplate>  
</ListBox> 

In the Hold event handler, the sender will be the StackPanel of the current ListBoxItem. The DataContext of the StackPanel is the view model item (it is like listbox.SelectedItem when an item is selected, however note that a hold gesture won't actually cause an item to be selected).

private void ListItem_Hold(object sender, GestureEventArgs e) 
        { 
            // sender is the StackPanel in this example 
            var holdItem = (sender as StackPanel).DataContext; 
 
            // holdItem has the type of the view model 
        } 

No comments:

Post a Comment