Aug 6, 2011

Handle OnClick Event in ListBox on Silverlight for Windows Phone 7

Generally on Windows Phone 7 using Silverlight You will use ListBox templates like this one

  1. <ListBox Margin="0,0,-12,0" ItemsSource="{Binding Items}" >  
  2.     <ListBox.ItemTemplate>  
  3.         <DataTemplate>  
  4.             <StackPanel Orientation="Horizontal" Margin="0,0,0,17"  
  5.                        MouseLeftButtonDown="StackPanel_MouseLeftButtonDown">  
  6.                 <Image Height="150" Width="150" Source="{Binding ImageSource}" Stretch="UniformToFill" />  
  7.                 <StackPanel Width="311">  
  8.                     <TextBlock Text="{Binding LineOne}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}"/>  
  9.                     <TextBlock Text="{Binding LineTwo}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}"/>  
  10.                 </StackPanel>  
  11.             </StackPanel>  
  12.         </DataTemplate>  
  13.     </ListBox.ItemTemplate>  
  14. </ListBox>  

But on touch based platform such as Windows Phone 7, MouseLeftButtonDown will trigger event, even if You try scroll ListBox content. Another aproach is to use ManipulationCompleted event. Event arguments have property named IsTapEvent, but in latest Silverlight SDK this property is declared as Protected. So You can see it in debugger at runtime, but cannot use in code.

What You can do is subscribe to ManipulationCompleted event, and check e.TotalManipulation for Scale and Transform properties equals zero.

  1. private void StackPanel_ManipulationCompleted(object sender, ManipulationCompletedEventArgs e)    
  2. {    
  3.     var zero = new Point(0,0);    
  4.     if( e.TotalManipulation.Scale == zero && e.TotalManipulation.Translation == zero )    
  5.         MessageBox.Show("gotcha!");    
  6. }    


  1. Mouse left button down ,mouse motion listner,onclick using silverlight is awesome hosting review

  2. In this case it not big difference from using OnSelectionChange, but rely on selection also have issue - item remains in selected state and second tap on item doesn't fire event.

    Anyway, thanks for opinion