简体   繁体   中英

WP8 LongListSelector event sequence

My app is a phonebook of sorts, listed by a LongListSelector and laid out by a DataTemplate (as you would expect). The template is defined in the page resources and it is thus no problem to bind an event handler to the tap event of one of its elements.

There are various things a user can do with an entry, depending on which element is tapped:

  • name: add to contacts
  • number: call the number
  • address: map location

The difficulty lies in determining which item was selected from the tap event of a template item , because the SelectionChanged event fires after the Tap event. At this stage SelectedItem has yet to be updated and contains the last selection, which may be null.

My current notion is to use Dispatcher to invoke an Action that then uses SelectedItem, essentially reproducing the "DoEvents" of ancient VB.

This works, but it's ugly as sin. Anyone got any better ideas?


You can't do the above in a Windows Store app. An equally ugly but technically undemanding solution that will work on both platforms is to declare a page level variable and set it in the tap handlers

string _pendingTap;

private void phoneNumber_Tapped(object sender, TappedRoutedEventArgs e)
{
  _pendingTap = "phoneNumber";
}

private void address_Tapped(object sender, TappedRoutedEventArgs e)
{
  _pendingTap = "address";
}

private void name_Tapped(object sender, TappedRoutedEventArgs e)
{
  _pendingTap = "name";
}

then use this information in the grid's ItemClick event handler

private void gridviewResult_ItemClick(object sender, ItemClickEventArgs e)
{
 var entry = e.ClickedItem as Entry; //hurrah, in scope!
 switch (_pendingTap)
  {
    case "name":
      //do whatever you do with an entry when the name is tapped (eg add to contacts)
      break;
    case "address":
      //do whatever you do with an entry when the address is tapped (eg map)
      break;
    case "phoneNumber":
      //do whatever you do with an entry when the name is tapped (eg call number)
      break;
  }
  _pendingTap = null;
}

When I say it will work on both platforms, I mean you can use exactly the same approach. Unfortunately both the names and signatures for tap events differ between the platforms.

If the tapped elements are inside the LongListSelector , could you use commands on the elements so that? (For example: http://www.geekchamp.com/articles/how-to-bind-a-windows-phone-control-event-to-a-command-using-mvvm-light )

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