我有一个列表框及其数据模板。列表框的项目与静态源绑定。在数据模板中,我有一个按钮,并创建了它的上下文菜单和一些菜单项。
<ObjectDataProvider x:Key="GlobalUnits"/>
<DataTemplate x:Key="listboxTemplate" DataType="UnitClass">
<StackPanel Margin="3" >
<DockPanel >
<Button DockPanel.Dock="Left" Margin="5,0,10,0">
<Button.ContextMenu>
<ContextMenu x:Name="CMUnits" Opened="OnContextMenuOpened"
MenuItem.Click="OnMenuItemClick">
<MenuItem Header="Add"
x:Name="MenuItemName" />
<MenuItem Header="Delete"
x:Name="MenuItemDelete" />
</ContextMenu>
</Button.ContextMenu>
</Button>
</DockPanel>
</StackPanel>
</DataTemplate>
<ListBox x:Name="TUListBox"
local:DragDropManager.DragSourceAdvisor="{StaticResource sourceAdvisor}"
ItemTemplate="{DynamicResource listboxTemplate}"
ItemsSource="{Binding Source={StaticResource GlobalUnits}}"/>
In Code behind:
void OnMenuItemClick(object sender, RoutedEventArgs e)
{
if (e.Source == this.MenuItemDelete) <//error here MenuItemDelete is not available
{
}
}
我已在datatemplate中将MenuItemDelete定义为menuitem按钮。任何建议,如果我在正常的xaml代码中将上下文菜单放在datatemplate之外就可以了。
当我在运行时单击菜单项时,我的程序调试光标甚至没有到达OnMenuItemClick事件
感谢。
答案 0 :(得分:0)
您的问题有更好的解决方案,涉及使用命令(您应该查看),但这是我创建的一个示例,演示了这个工作。这是XAML:
<Window x:Class="TestWpfApplication.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window15" Height="300" Width="300"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Window.Resources>
<DataTemplate x:Key="testTemplate">
<StackPanel Margin="3">
<DockPanel>
<Button DockPanel.Dock="Left" Margin="5,0,10,0" Content="{Binding}">
<Button.ContextMenu>
<ContextMenu x:Name="CMUnits" MenuItem.Click="OnMenuItemClick">
<MenuItem Header="Add"
x:Name="MenuItemAdd" />
<MenuItem Header="Delete"
x:Name="MenuItemDelete" />
</ContextMenu>
</Button.ContextMenu>
</Button>
</DockPanel>
</StackPanel>
</DataTemplate>
</Window.Resources>
<Grid>
<ListBox ItemTemplate="{StaticResource testTemplate}"
ItemsSource="{Binding TestItems}"/>
</Grid>
</Window>
以下是代码隐藏:
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
public ObservableCollection<string> TestItems
{
get
{
return new ObservableCollection<string>()
{
"Item 1", "Item 2", "Item 3"
};
}
}
private void OnMenuItemClick(object sender, RoutedEventArgs e)
{
MenuItem item = e.Source as MenuItem;
if (item.Name == "MenuItemDelete")
{
// Delete the item.
}
else if (item.Name == "MenuItemAdd")
{
// Add the item.
}
}
}