简体   繁体   中英

Adding Context menu to DataTemplate Items in wp7

How can I Add the context menu Programatically where Conrol (DepedencyObject) are Created in Data Template in xaml?

XAML:

<ListBox x:Name="sampleListBox"
            ItemsSource="{Binding SomeCollection}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel x:Name="sp">
                <TextBlock Text="{Binding Value}" />
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Code:

void Initilize()
{
     ContextMenu cm = new ContextMenu();
     cm.Items.Add(new MenuItem());

     ContextMenuService.SetContextMenu( 
              // I am not geting the DepedencyObject as a parameter and 
              // depedency Object has to passed. 
              // My Qyestion is how to get the Stack pannel here.
     , cm);

}

Why not use XAML to assign ContextMenu to the StackPanel ? And if you want to customize you ContextMenu , register to its Loaded event.

Example:

<ListBox x:Name="samleListBox"
            ItemsSource="SomeCollection">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel x:Name="sp">
                <toolkit:ContextMenuService.ContextMenu>
                    <toolkit:ContextMenu Loaded="OnContextMenuLoaded" />
                </toolkit:ContextMenuService.ContextMenu>
                <TextBlock Text="{Binding Value}" />
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM