Get Selected Item from Windows Phone listbox in Ho

2019-08-10 22:21发布

问题:

I have a pretty basic Listbox in my Windows phone 8 app. It's not data bound to anything, it's just an empty listbox.

<ListBox Margin="0,10" Name="lstStops" SelectionChanged="favouriteSelection" 
 Hold="favouriteSelectionHold" FontSize="28">
    <ListBox.Items>

    </ListBox.Items>
</ListBox>

I want to be able to give the user the option to delete items from this list by pressing and holding on the item. I have added an onHold event which is firing when the user presses on an item in the list and holds but I don't know how to find out which actual entry in the listbox they have selected.

How can I find out which item they have pressed and held on?

This is how the Listbox is populated:

foreach (KeyValuePair<string, Object> entry in IsolatedStorageSettings.ApplicationSettings)
{
    lstStops.Items.Add(entry.Key as String + " - " + entry.Value as String);
}

回答1:

It's been asked many times. There are different ways to achieve this. Read more here.

One way includes getting the datacontext of the sender and casting it to your Item type.

EDIT: Since it's a bunch of strings, the way to extract the string can be:

private void favouriteSelectionHold(object sender, System.Windows.Input.GestureEventArgs e)
{
    string n = (e.OriginalSource as TextBlock).Text;
}

This works only if your DataTemplate is not defined differently.