我有一个自定义控件AsGridItem
,这是一个自定义按钮,正在实用地创建并添加到WrapPanel
中。我需要帮助才能在其上完全实现上下文菜单,以便可以从数据库中删除引用的项,甚至可以打开新窗口或显示弹出窗口。
private void LoadItems(List<MyItems> items)
{
foreach (item in items)
{
AsGridItem asGrid = new AsGridItem();
asGrid.Title = item.Title;
asGrid.Icon = item.IconName;
asGrid.PackIcon = item.ContentType;
MenuItem editMenu1 = new MenuItem();
editMenu1.Header = "Open this Item";
editMenu1.Click += ItemOpen_Click;
MenuItem editMenu2 = new MenuItem();
editMenu2.Header = "Delete this Item";
editMenu2.Click += ItemDelete_Click;
MenuItem editMenu3 = new MenuItem();
editMenu3.Header = "View Properties";
editMenu3.Click += ItemProperties_Click;
ContextMenu contextMenu = new ContextMenu();
contextMenu.Items.Add(editMenu1);
contextMenu.Items.Add(editMenu2);
contextMenu.Items.Add(editMenu3);
asGrid.ContextMenu = contextMenu;
asGrid.Click += GridItem_Click;
ItemsList.Children.Add(asGrid);
}
}
private void GridItem_Click(object sender, RoutedEventArgs e)
{
AsGridItem asGrid = sender as AsGridItem;
OpenItem(asGrid);
}
private void ItemOpen_Click(object sender, RoutedEventArgs e)
{
AsGridItem asGrid = sender as AsGridItem;
OpenItem(asGrid);
}
我是将对象设置为空引用的错误,无法弄清楚该如何解决。
答案 0 :(得分:0)
您获得的引用为空,因为您使用的是应在应引用的菜单项上单击onclick的代码,而菜单项则在包装面板中单击了该项目的上下文菜单。
菜单项>>上下文菜单>>项目
我刚刚修改了一些代码以实现此目的
private void ItemOpen_Click(object sender, RoutedEventArgs e)
{
//try to reference the menuItem first
MenuItem menuItem = (MenuItem)sender;
//then reference the contextmenu
ContextMenu contextMenu = (ContextMenu)menuItem.Parent;
// then your initial code can come in modfied like this
AsGridItem asGrid = (AsGridItem)contextMenu.PlacementTarget;
OpenItem(asGrid);
}
希望它能解决您的null引用错误问题