hendra.dev

A work in progress

Windows Phone – Context Menu on a ListBox

Written on

Ok, I have been working on updating one of my windows phone app, Swatch 7. I added a feature that allows user to save the color they picked. I have write more on that on another post, maybe after the app on the marketplace is updated. So, to remove one finished doing that, but I’llof the saved color, I used the context menu provided with the windows phone toolkit. It’s a bit different in the way that I can’t access the selected item of the ListBox the ordinary way ( the selectedIndex returns –1, so that means holding down a listbox item doesn’t count as selecting it). So, I need a way to get information about which item to remove, and after a bit of internet search, here is how I do it:

:::xml
<ListBox Name="paletteList">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Grid Margin="4">
                <toolkit:ContextMenuService.ContextMenu>
                    <toolkit:ContextMenu>
                        <toolkit:MenuItem Header="Delete" Name="removeFromPalette"
                                        Click="removeFromPalette_Click"/>
                    </toolkit:ContextMenu>
                </toolkit:ContextMenuService.ContextMenu>
            </Grid>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Those are the code to set the context menu for the listbox, and here is how the C# code on the click event:

:::csharp
private void removeFromPalette_Click(object sender, RoutedEventArgs e)
{
    Item selectedItem = (sender as MenuItem).DataContext as Item;
    // Do whatever with the selectedItem
}