我有一个带有绑定到ViewModel的DataContext的Window。 在我的ViewModel中,我有一个名为例如
的命令HideShowSingleWindow
我的窗口有一个动态填充的托盘icont的上下文菜单。现在我需要将MenuItem上的Command单击到Window datacontext中的HideShowSingleWindow命令。
我试过
<Grid>
<tb:TaskbarIcon
IconSource="/Icons/main.ico"
ToolTipText="SCADA Control Center"
DoubleClickCommand="{Binding Path=HideShow}">
<tb:TaskbarIcon.ContextMenu>
<ContextMenu>
<ContextMenu.ItemsSource>
<CompositeCollection>
<MenuItem Header="Windows" ItemsSource="{Binding Path=RegisteredWindows}">
<MenuItem.ItemContainerStyle>
<Style TargetType="{x:Type MenuItem}">
<Setter Property="Header" Value="{Binding Path=Title}" />
<Setter Property="IsCheckable" Value="True" />
<Setter Property="IsChecked" Value="{Binding Path=IsLoaded, Mode=OneWay}"/>
<Setter Property="Command" Value="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContextMenu}}, Path=HideShowSingleWindow}" />
<Setter Property="CommandParameter" Value="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContextMenu}}, Path=PlacementTarget.SelectedItem}" />
</Style>
</MenuItem.ItemContainerStyle>
</MenuItem>
<MenuItem Header="Show/Hide All" Command="{Binding Path=HideShow}" />
<Separator />
<MenuItem Header="Exit" Command="{Binding Path=Quit}" />
</CompositeCollection>
</ContextMenu.ItemsSource>
</ContextMenu>
</tb:TaskbarIcon.ContextMenu>
</tb:TaskbarIcon>
</Grid>
我们可以看到:
<Setter Property="Command" Value="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContextMenu}}, Path=HideShowSingleWindow}" />
但它没有用。
答案 0 :(得分:4)
ContextMenu不会继承tb:TaskbarIcon
的DataContext,因为上下文菜单与其展示位置目标不在同一个Visual树中(任务栏图标在你的情况)。
因此,显式获取DataContext并使用以下命令绑定:
<Setter Property="Command"
Value="{Binding RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type ContextMenu}},
Path=PlacementTarget.DataContext.HideShowSingleWindow}"/>
答案 1 :(得分:0)
尝试按如下方式修改setter:
<Setter Property="Command" Value="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type tb:TaskbarIcon}}, Path=DataContext.HideShowSingleWindow}" />