我正在尝试修改ContextMenu
可编辑单元格上XamNumericEditor
的默认XamDataGrid
。
这是我的XAML代码:
<igDP:XamDataGrid.Resources>
<Style TargetType="{x:Type editors:XamNumericEditor}">
<Setter Property="ContextMenu">
<Setter.Value>
<ContextMenu>
<ContextMenu.Items>
<MenuItem Header="Select All"
Command="SelectAll">
<MenuItem.Icon>
<Image Source="..\icons\table_select_all.png"/>
</MenuItem.Icon>
</MenuItem>
<MenuItem Header="Accept for column"
Click="MenuItem_Click">
</MenuItem>
</ContextMenu.Items>
</ContextMenu>
</Setter.Value>
</Setter>
</Style>
</igDP:XamDataGrid.Resources>
代码隐藏文件包含此MenuItem的事件函数:
private void MenuItem_Click(object sender, RoutedEventArgs e)
{
//...
}
但是当我启动它时,我会收到一条带有消息的异常: 无法将“System.Windows.Controls.MenuItem”类型的对象强制转换为“System.Windows.Controls.ContextMenu”。
你可以帮帮我吗?感谢。答案 0 :(得分:13)
尝试将ContextMenu
添加为资源,并将其引用为StaticResource
我没有安装XamDataGrid
所以我无法尝试,但它应该是以下几行。
<igDP:XamDataGrid.Resources>
<ContextMenu x:Key="contextMenu">
<ContextMenu.Items>
<MenuItem Header="Select All"
Command="SelectAll">
<MenuItem.Icon>
<Image Source="..\icons\table_select_all.png"/>
</MenuItem.Icon>
</MenuItem>
<MenuItem Header="Accept for column"
Click="MenuItem_Click"></MenuItem>
</ContextMenu.Items>
</ContextMenu>
<Style TargetType="{x:Type editors:XamNumericEditor}">
<Setter Property="ContextMenu" Value="{StaticResource contextMenu}"/>
</Style>
</igDP:XamDataGrid.Resources>
或者,您可以使用EventSetter
<MenuItem Header="Accept for column">
<MenuItem.Style>
<Style TargetType="MenuItem">
<EventSetter Event="Click" Handler="MenuItem_Click"/>
</Style>
</MenuItem.Style>
</MenuItem>
<强>更新强>
要获得PlacementTarget
,您需要ContextMenu
。您可以将其传递为CommandParameter
<MenuItem Header="Accept for column"
CommandParameter="{Binding RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}"
Click="MenuItem_Click">
</MenuItem>
private void MenuItem_Click(object sender, RoutedEventArgs e)
{
MenuItem menuItem = sender as MenuItem;
ContextMenu contextMenu = menuItem.CommandParameter as ContextMenu;
var placementTarget = contextMenu.PlacementTarget;
//...
}