如何以编程方式添加上下文菜单在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);
}
答案 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>