Silverlight 4: How do I find the original UI element from the context menu menuitem_click?
I have a datagrid and I added a silverlight 4 contextual context to a textbox in the datagrid as follows. When users right-click on a text box, a context menu is displayed. When users click on a menu item with the title "Test", "MenuItem_Click" is triggered. Now I want to access the textbox from MenuItem_Click and change its properties like background etc. Is there a way to find the textbox element (which is the parent of the contextmenu) from the MenuItem_Click event?
It seems to me that I am missing something very simple.
<my:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBox Text="{Binding AcctId}"
Style="{StaticResource documentTextBoxStyle}"
ToolTipService.ToolTip="Right Click to modify parameters" >
<toolkit:ContextMenuService.ContextMenu >
<toolkit:ContextMenu >
<toolkit:MenuItem Header="Test" Click="MenuItem_Click"/>
</toolkit:ContextMenu>
</toolkit:ContextMenuService.ContextMenu>
</TextBox>
</DataTemplate>
a source to share
All I can suggest is to give your MenuItem a tag with its parent TextBlock like this: EDIT: Can't figure out how to insert into Xaml, but I'm sure you know how to add this.
Then, in the click event, you will find the TextBlock:
private void MenuItem_TextBlockClick(object sender, RoutedEventArgs e)
{
MenuItem menuItem = (MenuItem)sender;
TextBlock textBlock = this.FindName((string)menuItem.Tag) as TextBlock;
/// do something
}
The problem I found was the parent of the MenuItem, it is the ContextMenu and that's ok. But once you try to get the parent of the ContextMenu, it just works.
a source to share
Although I didn't find a solution for this, I did find a couple of workarounds
- Swipe the visual tree and find the text box
- Modify the code in the management instrumentation sources to expose the internal Owner as a public property that contains a link to the owner of the context menu, in my case a textbox.
I wonder why the guys at SL Toolkit made the owner internal and not public. Probably their idea is to manage the "ContextMenu" only through the "ContextMenuService", but unfortunately the ContextMenuService doesn't give the Owner. Hopefully the guys at the SL toolbox give us the opportunity to get the owner of the context menu in future releases.
a source to share