2012-04-04 118 views
1

我有一個窗口,其中包含UserControl1和UserControl2。這些用戶控件擁有自己的視圖模型。此外,這些用戶控件使用UserControl3來顯示數據。因此,當UserControl1使用UserControl3時,UserControl3具有與UserControl1相同的視圖模型。WPF usercontrol命令綁定到窗口viewmodel

我在UserControl3中有一個綁定,我想調用UserControl1的viewmodel上的命令。

但我找不到一種方法使其工作。歡迎任何幫助。非常感謝你。

這裏是我的約束力不工作:

<UserControl x:Class="MyNamespace.UserControl3"    
     xmlns:local="clr-namespace:MyNamespace">  
<UserControl.Resources>   
    <DataTemplate DataType="{x:Type g:GraphNode}"> 
     <StackPanel>    
      <StackPanel.ContextMenu> 
       <ContextMenu> 
        <MenuItem Header="My Command" Command="{Binding Path=DataContext.MyCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type local:UserControl3}}}"/> 
       </ContextMenu> 
      </StackPanel.ContextMenu>    
      <Grid> 
       <ContentControl Content="{Binding Data}"/>      
      </Grid> 
     </StackPanel>    
    </DataTemplate>  
</UserControl.Resources> 

回答

1

這工作在我的應用程序:

<DataTemplate DataType="{x:Type g:GraphNode}"> 
     <StackPanel Tag="{Binding}"> 
      <StackPanel.ContextMenu> 
       <ContextMenu> 
        <MenuItem Header="My Command" Command="{Binding Path=PlacementTarget.Tag.MyCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ContextMenu}}" /> 
       </ContextMenu> 
      </StackPanel.ContextMenu> 
     </StackPanel> 
    </DataTemplate> 

的關鍵是ContextMenus是在不同的窗口,讓你不能像通常那樣訪問數據環境。
您必須對其進行調整,以便將包含您尋求的Command的對象設置爲StackPanel(即ContextMenuPlacementTarget)的標籤。

相關問題