user1775297
user1775297

Reputation: 87

Windows Phone app - get index of item that called context menu

I have a ListBox with a context menu in it

<ListBox>

<toolkit:ContextMenuService.ContextMenu>

<toolkit:ContextMenu IsZoomEnabled="True"x:Name="ContextMenu" >

<toolkit:MenuItem x:Name=”Open" Header=”Open Trailer" Click="nOpe_Click"/>



</toolkit:ContextMenu>

</toolkit:ContextMenuService.ContextMenu>


</ListBox>

How do i get the Index of the ListBox Item that called the Open_Click event.

Upvotes: 0

Views: 1046

Answers (1)

dBlisse
dBlisse

Reputation: 811

Your Open_Click event should have an Object sender in its signature. This is what you have to work with.

Take the sender and cast it to the MenuItem. This MenuItem will have a DataContext

The DataContext of this MenuItem should be an item in your ListBox.

If you have a reference to that ListBox, then you can go

var contextMenuOpenedIndex = ListBoxName.IndexOf((sender as MenuItem).DataContext)

Here's the same question (and a reference): ListBox.SelectedIndex in ContextMenu event handler

A sample ItemTemplate:

<ListBox x:Name="SampleListBox">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Grid>
                <TextBlock Text="{Binding}">
                ... ContextMenu ... 
            </Grid>
        </DataTemplate>    
    </ListBox.ItemTemplate>
</ListBox>

Upvotes: 1

Related Questions