无法将事件处理程序附加到Style中的上下文菜单项

时间:2011-03-24 20:08:33

标签: wpf xaml event-handling styles infragistics

我正在尝试修改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”。

你可以帮帮我吗?感谢。

1 个答案:

答案 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;
    //...
}