Search code examples
c#silverlightwindows-phone-7xamlsilverlight-toolkit

How to change the properties of a contextmenu in a datatemplate in WP7?


What I want
change the properties(e.g. background) of a context menu in a datatemplate in the runtime from the code behind.

What is the XAML

<DataTemplate x:Key="ListsDataTemplate">
    <StackPanel x:Name="stackPanel" Margin="0,0,0,10">
        <toolkit:ContextMenuService.ContextMenu> 
            <toolkit:ContextMenu x:Name="myMenu" IsFadeEnabled="False" IsZoomEnabled="False">
                        <toolkit:MenuItem x:Name="edit" Header="{Binding LocalStrings.bt_menu_Edit, Source={StaticResource LocalizedResources}}" Click="menuItemEdit_Click" />
                        <toolkit:MenuItem x:Name="postpone" Header="{Binding LocalStrings.bt_menu_Postpone, Source={StaticResource LocalizedResources}}" Click="menuItemPostpone_Click" />
                        <toolkit:MenuItem x:Name="email" Header="{Binding LocalStrings.bt_menu_Email, Source={StaticResource LocalizedResources}}" Click="menuItemEmail_Click" />
                        <toolkit:MenuItem x:Name="sms" Header="{Binding LocalStrings.bt_menu_Sms, Source={StaticResource LocalizedResources}}" Click="menuItemSMS_Click" />                        
                </toolkit:ContextMenu> 
        </toolkit:ContextMenuService.ContextMenu>

        <ListBox    
            HorizontalAlignment="Left" 
            DataContext="{Binding}" 
            ItemTemplate="{StaticResource ListsDataTemplate}" 
            VerticalAlignment="Top" 
            Width="432" 
            Margin="0,81,0,0" 
            x:Name="myListBox">
        </ListBox>

Solution

  • Add a Loaded="myMenu_Loaded" handler to myMenu, and in that handler declare var myMenu = (ContextMenu)sender;.

    Since myMenu is in a DataTemplate and is a template for creating objects rather than the instance that will actually be used on the page, no field is auto-generated for it.