0

I have a collection of objects which i display in a databound listbox. The listbox contains the template which is defined as a StackPanel whcih contains a TextBlock. The TextBlock shows my data bounded from collection.

I am also associating the contextmenu using Silverlight toolkit for Windows Phone. I am associating ContextMenu and MenuItems programmatically to the selected TextBlock. I am handling every menu item by its own click event.

The problem that i face is that when i click the menuitem from contextmenu, i cannot get the referenced control from the listbox. In other words, I am not able to get the reference to TextBlock through which the contextmenu is displayed.

Magnus Johansson
  • 28,010
  • 19
  • 106
  • 164
Uday0119
  • 770
  • 1
  • 7
  • 23

1 Answers1

0

I think there's a method to get the element associated to a given ContextMenu, but as I can't find it, here's a workaround.

You say you are associating the ContextMenu with the TextBlock programatically. Then, you can use the wonderful Tag property to hold a reference to your TextBlock. As you can read in the link, Tag holds any arbitrary object. The code would go like this:

First, you set the tag to your textblock (I'm using some generic names)

menuitem.Tag = textblock;

and then, in the click handler, retrieve that Textblock

var menuItem = sender as MenuItem;
if(menuItem != null && menuItem.Tag is TextBlock)
   var textBlock = menuItem.Tag as TextBlock;

Then, textBlock is the TextBlock that called the ContextMenu.

Hope it helped.

gjulianm
  • 834
  • 7
  • 22
  • There's no way in ContextMenu class to get the referenced comtrol. However for desktop wpf/silverlight, there is a PlacementTarget property that may help in getting the referenced control...
    well thanx for the answer. I mark this once i try it. Bcoz its impotant to me. Thax anyways...:)
    – Uday0119 Jun 03 '12 at 16:44