WPF XAML - 将上下文菜单项绑定到主窗口数据上下文

本文关键字:上下文 窗口 数据 绑定 菜单项 XAML WPF | 更新日期: 2023-09-27 17:55:43

我有一个窗口,其中DataContext绑定到ViewModel。在我的视图模型中,我有一个命令,例如

HideShowSingleWindow

我的窗口有一个动态填充的托盘图标的上下文菜单。现在,我需要将菜单项单击上的命令绑定到窗口数据上下文中的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}" />

但它不起作用。

WPF XAML - 将上下文菜单项绑定到主窗口数据上下文

ContextMenu 不会继承 tb:TaskbarIcon 的 DataContext,因为上下文菜单与其放置目标在您的情况下为任务栏图标)的可视化树中不在同一可视化树中。

因此,显式获取 DataContext 并使用如下所示的命令绑定:

<Setter Property="Command"
        Value="{Binding RelativeSource={RelativeSource FindAncestor,
                         AncestorType={x:Type ContextMenu}}, 
                       Path=PlacementTarget.DataContext.HideShowSingleWindow}"/>

尝试按如下方式修改资源库:

<Setter Property="Command" Value="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type tb:TaskbarIcon}}, Path=DataContext.HideShowSingleWindow}" />