1

左クリックするUserControlButton開く内部があります。の親をアイテムのコマンドにパラメーターとしてContextMenu渡して、そのウィンドウを閉じようとしていますが、役に立ちません。とですべてを試しましたが、パラメーターは常に null です。親ウィンドウの一部ではないことは承知しています。私は現在、このアプローチに固執していますが、機能していません。UserControlWindowContextMenuRelativeSourcePlacementTargetContextMenuVisualTree

<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>

Command は、 で定義されている参照コマンドですUserControl.Resources:

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

実行部分がトリガーされますが、パラメーターは常にnullです。CommandParameterだから、私の質問は、の時点で親ウィンドウをバインドする正しい方法は何ですかMenuItem. このことはほぼ2日間私を悩ませているので、助けていただければ幸いです。

4

1 に答える 1

2

ここでの正しい方法は、親を VM に として渡さないことです。これが MVVM の場合は、Messenger(MVVM Light) / EventAggregator(Prism) アプローチを使用して、コマンドがトリガーされて Close されたときに Message を のコード ビハインドに送信する必要があります。WindowCommandParameterWindow

VM での参照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" />
...

アップデート:

リンクをダウンロード

から「Exit」コマンドを実行すると、出力ウィンドウにContextMenu表示されます。Sender Object: MvvmLight16.MainWindowこの出力は VM から送信されます。

于 2013-06-19T11:59:33.420 に答える