Search code examples
c#.netsilverlightsilverlight-toolkit

Silverlight 4: How to find source UI element from contextmenu's menuitem_click?


I have a datagrid and I added silverlight 4 toolkit contextmenu to textbox in datagrid as follows. When users right click on the textbox, contextmenu is being displayed. When users click the menu item with Header "Test", "MenuItem_Click" is getting executed. Now I want to access the textbox from the MenuItem_Click and modify its properties like background etc. Is there anyway to find textbox element(which is contextmenu's parent) from MenuItem_Click event?

It appears 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>


Solution

  • There's really no need for a workaround, it's as simple as using the databinding:

    (sender as MenuItem).DataContext as TextBox
    

    Will give you the TextBox you're after. (Storing stuff in the Tag field is really not something you want to clutter your code with.)