2013-06-19 58 views
1

我有一個UserControlButton,其中單擊左鍵打開ContextMenu。我試圖通過UserControl的父母Window作爲參數ContextMenu項目的命令關閉該窗口,但無濟於事。我嘗試了所有與RelativeSourcePlacementTarget,但參數始終爲空。我知道ContextMenu不是父窗口的VisualTree的一部分。我目前堅持這種方法,但它不工作。WPF UserControl - 將父窗口作爲命令參數綁定到ContextMenu MenuItem

<Grid x:Name="LayoutRoot"> 
     <Button 
      HorizontalAlignment="Left" 
      Margin="0" 
      Style="{DynamicResource ButtonStyle1}" 
      VerticalAlignment="Top" 
      Width="120" 
      Height="25" 
      Content="Dashboard Menu" 
      TextElement.FontWeight="Bold" 
      Foreground="AliceBlue"    
      > 

      <!--Tag="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={ x:Type Window}}}"--> 
      <Button.ContextMenu> 
       <ContextMenu DataContext="{Binding PlacementTarget, RelativeSource={RelativeSource Self}}" > 
        <MenuItem Header="Open Log Viewer" Command="{StaticResource openLogViewer}" /> 
        <Separator /> 
        <MenuItem Header="Exit" Command="{StaticResource exit}" CommandParameter="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource AncestorType=Window}}"/> 
       </ContextMenu> 
      </Button.ContextMenu> 
     </Button> 
    </Grid> 

命令在UserControl.Resources定義引用命令:

<my:CommandReference x:Key="exit" Command="{Binding Exit}" /> 

和它的執行部分被觸發,但參數始終是零。所以,我的問題是,什麼是正確的方式來綁定父窗口爲 MenuItem。任何幫助表示讚賞,因爲這件事困擾了我近兩天。

回答

1

就在這裏的方式是不Window到VM作爲CommandParameter。如果這是MVVM,當命令觸發關閉它時,您應該使用Messenger(MVVM Light)/ EventAggregator(Prism)方法向Window的代碼隱藏發送消息。

在虛擬機中引用Window顯然是錯誤的。

僅供參考,你的努力做 「可以做」

類似:

<Grid x:Name="LayoutRoot"> 
    <Button HorizontalAlignment="Left" 
      Margin="0" 
      Style="{DynamicResource ButtonStyle1}" 
      VerticalAlignment="Top" 
      Width="120" 
      Height="25" 
      Content="Dashboard Menu" 
      TextElement.FontWeight="Bold" 
      Foreground="AliceBlue" 
      Tag="{Binding RelativeSource={RelativeSource FindAncestor, 
                 AncestorType={x:Type Window}}}"> 
    <Button.ContextMenu> 
     <ContextMenu> 
     <MenuItem Header="Open Log Viewer" Command="{StaticResource openLogViewer}" /> 
     <Separator /> 
     <MenuItem Command="{StaticResource exit}" 
        CommandParameter="{Binding PlacementTarget.Tag, 
              RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}" 
        Header="Exit" /> 
... 

更新:

Download Link

在執行「退出「來自ContextMenu的命令,您應該在Output Windo中看到Sender Object: MvvmLight16.MainWindow W上。該輸出從VM發送。

+0

感謝您的解釋,但這是我嘗試的第一種方法,它不起作用。我知道當我將父窗口傳遞給VM時我打破了MVVM模式,但我沒有使用任何MVVM工具箱。 – wannjanjic

+0

@wannjanjic我已經更新了我的答案,下載了一個使用我說過的方法的樣本,它對我來說工作正常。那麼如果你沒有使用任何MVVM工具包,也許你應該考慮使用一個比MVVM。而不是使用MVVM tbh。 – Viv

+0

@wannjanjic從你的ContextMenu中刪除'DataContext =「{Binding PlacementTarget,RelativeSource = {RelativeSource Self}}」''。不知道爲什麼你甚至需要 – Viv