views:

39

answers:

2

What is the best way to make a menu of options in wp7? (Not a context menu or app bar.) Currently I'm using a ListBox of strings, but I'm not sure if that's the way to go.

I'm also not entirely sure how to make make the ListBox entries respond to tapping such that they navigate to another page.

A: 

You can add a listener to the selection change event on the listbox, and then use the NavigationService to navigate wherever you want based on the selected item.

John Gardner
+1  A: 

For a simple menu I've used someting like the following several times.

<ListBox SelectionChanged="LinkSelected">
    <ListBoxItem Name="EnterCode" >
        <TextBlock Text="Enter Code"  />
    </ListBoxItem>
    <ListBoxItem Name="Login" >
        <TextBlock Text="Login" />
    </ListBoxItem>
    <ListBoxItem Name="Register" >
        <TextBlock Text="Register" />
    </ListBoxItem>
</ListBox>

And then something like this in the event handler:

private void WelcomeLinkSelected(object sender, SelectionChangedEventArgs e)
{
    if (sender is ListBox)
    {
        if ((sender as ListBox).SelectedIndex < 0)
        {
            return;
        }

        if ((sender as ListBox).SelectedIndex == 0)
        {
            NavigationService.Navigate(new Uri("/EnterCode.xaml", UriKind.Relative));
        }

        if ((sender as ListBox).SelectedIndex == 1)
        {
            NavigationService.Navigate(new Uri("/Login.xaml", UriKind.Relative));
        }

        if ((sender as ListBox).SelectedIndex == 2)
        {
            NavigationService.Navigate(new Uri("/Register.xaml", UriKind.Relative));
        }

        // This is very important!
        (sender as ListBox).SelectedIndex = -1;
    }
}

If you do this, the last line in the event handler, which resets the SelectedIndex, is very important as it allows the same menu item to be selected multiple times in a row without first selecting another option.

Matt Lacey
Why all the `(sender as ListBox)` instead of just casting once?
Rosarch
@Rosarch yes, you could just cast one. example was ripped out of some old code which was also doing lots fo other things.
Matt Lacey