我有一個Window,DataContext綁定到ViewModel。 在我的ViewModel我有一個名爲例如WPF XAML - 將上下文菜單項綁定到主窗口DataContext
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}" />
,但它不工作。
它不工作。 我收到此錯誤消息: 「System.Windows.Data錯誤:4:無法找到與參考綁定的源'RelativeSource FindAncestor,AncestorType ='Hardcodet.Wpf.TaskbarNotification.TaskbarIcon',AncestorLevel =''。BindingExpression: Path = DataContext.HideShowSingleWindow; DataItem = null;目標元素是'MenuItem'(Name ='');目標屬性是'Command'(類型'ICommand')「 – rPulvi
責備我:我應該知道'因爲我撞到了成千上萬次! Rohit給你正確的答案... –