将上下文菜单添加到wp7中的DataTemplate项

时间:2011-01-24 08:19:31

标签: silverlight windows-phone-7

如何以编程方式添加上下文菜单在xaml中的数据模板中创建Control(DependencyObject)的位置?

XAML:

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

代码:

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);

}

1 个答案:

答案 0 :(得分:3)

为什么不使用XAML将ContextMenu分配给StackPanel?如果您想自定义ContextMenu,请注册其Loaded事件。

实施例

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