上下文菜单菜单项单击数据上下文
本文关键字:上下文 数据 单击 菜单项 菜单 | 更新日期: 2023-09-27 18:37:19
我有一个对象的集合,我创建了一个要显示的ScrollViewer。 对于每个对象,数据显示在网格中,我在其中添加了上下文菜单,以便当用户右键单击网格时,他们可以更改对象的属性。 我无法弄清楚如何知道右键单击了哪个对象。
在下面的代码中,我如何知道当到达菜单项"关闭"的回调时右键单击了哪个"电压监视器"?
<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>