上下文菜单 MenuItem 单击数据上下文?

Context Menu MenuItem Click Data Context?

我有一个对象集合,我创建了一个 ScrollViewer 来显示这些对象。对于每个对象,数据显示在我添加了上下文菜单的网格中,以便当用户右键单击网格时,他们可以更改对象的属性。我不知道如何知道哪个对象被右键单击了。

在下面的代码中,当到达 MenuItem "TurnOff" 的回调时,我如何知道哪个 "VoltageMonitor" 被右键单击?

<ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Hidden" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.ColumnSpan="2" Margin="0,0,0,15">
        <ItemsControl Name="icVoltageMonitorsPanel" ItemsSource="{Binding AppMonitors.VoltageMonitors, Mode=TwoWay}" Grid.ColumnSpan="2" Padding="0" Margin="0"  Width="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ScrollViewer}}, Path=ActualWidth}">
            <ItemsControl.ItemTemplate>
                <DataTemplate DataType="local:VoltageMonitor">
                    <Grid Height="130" Name="grdIndicator" Width="200" MinWidth="200" MinHeight="130">
                        <Grid.ContextMenu>
                            <ContextMenu>
                                <MenuItem Header="Edit Format..." />
                                <MenuItem Header="Turn off" Click="MenuItem_Click" DataContext=""/>
                            </ContextMenu>
                        </Grid.ContextMenu>
                        <Grid.RowDefinitions>
                            <RowDefinition Height="30*" />
                            <RowDefinition Height="25*" />
                            <RowDefinition Height="25*" />
                            <RowDefinition Height="25*" />
                            <RowDefinition Height="25*" />
                        </Grid.RowDefinitions>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="133*" />
                            <ColumnDefinition Width="67*" />
                        </Grid.ColumnDefinitions>

假设您已经在视图模型中定义了一个 ICommand,您可以这样做:

<ItemsControl ...>
      <ItemsControl.ItemTemplate>
          <DataTemplate DataType="local:VoltageMonitor">
              <Grid ..>
                  <Grid.ContextMenu>
                      <ContextMenu>
                          <MenuItem Header="Edit Format..." />
                          <MenuItem Header="Turn off" 
                              CommandParameter="{Binding}"
                              Command="{Binding RelativeSource=
                                   {RelativeSource Mode=FindAncestor, 
                                      AncestorType={x:Type ItemsControl}}, 
                                    Path=DataContext.TurnOffCommand}"/>
                      </ContextMenu>
                  </Grid.ContextMenu>