[英]WPF XAML - Bind Context Menu Item to Main Window DataContext
我有一個DataContext綁定到ViewModel的窗口。 在我的ViewModel中,我有一個命令,例如
HideShowSingleWindow
我的窗口有一個用於動態填充任務欄圖標的上下文菜單。 現在,我需要將MenuItem單擊上的Command綁定到Window數據上下文中的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}" />
但這不起作用。
ContextMenu不繼承tb:TaskbarIcon
DataContext,因為上下文菜單與其放置目標 ( 在您的情況下為任務欄圖標 ) 不在同一個Visual樹中 。
因此,顯式獲取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}" />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.