Reputation: 7949
I'm looking for a method - if at all possible - of removing a MenuItem control from a ContextMenu in Windows Phone 7.
Here's a simplified version of my XAML:
<ListBox>
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
[ -- Content -- ]
<toolkit:ContextMenuService.ContextMenu>
<toolkit:ContextMenu>
<toolkit:MenuItem Header="view attributes" Tag="ATTRIBUTES" Click="ViewSelectedResultAttributes" />
<toolkit:MenuItem Header="view groups" Tag="GROUPS" Click="ViewSelectedResultGroups" />
<toolkit:MenuItem Header="view webpage" Tag="ONLINE" Click="ViewWebPage" />
</toolkit:ContextMenu>
</toolkit:ContextMenuService.ContextMenu>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Now, not all of the items in the bound collection have a website associated with them, and for those items I wish to remove the MenuItem with the tag ONLINE (i.e. the last MenuItem).
But I can't find a way of achieving this.
I've also thought of adding the ContextMenu and all the MenuItems programmatically so that I could conditionally add each MenuItem but I can't seem to find an event such as OnItemDataBound or OnDataBinding, etc.
Can anyone help me out?
UPDATE: just to be more specific, I don't want to remove a MenuItem from the ContextMenu on every bound item in the ListBox, I only want to remove a MenuItem on specific items in the ListBox when the bound object fails a condition.
Let's say my ListBox contains 3 bound items: ListItem_1, ListItem_2, ListItem_3
Now, let's say that the object bound to ListItem_2 has one of its properties as NULL; In this case ListItem_2 should have one of the MenuItem controls from its ContextMenu removed, whereas ListItem_1 and ListItem_3 should still have this MenuItem.
What would be ideal is an event which allows me to capture each item as it's being bound, and which also exposes the ContextMenu. The ListBox.Items collection simply returns the same collection of objects that I assigned to be the data source, whereas a collection of, say, ListBoxItems would be more useful - does this exist?
Upvotes: 0
Views: 651
Reputation: 39007
First, give a name to your context menu to be able to retrieve it easily from the code-behind:
<toolkit:ContextMenu x:Name="ContextMenu">
From there, you can access the items using this.ContextMenu.Items
. So just remove the ones you don't need anymore:
var item = this.ContextMenu.Items.OfType<MenuItem>().First(m => (string)m.Tag == "ONLINE");
this.ContextMenu.Items.Remove(item);
Upvotes: 2