Life is Really Short, Have Your Life!!

ござ先輩の主に技術的なメモ

DataGridのContextMenuでUIElementが取得できない問題

stackoverflow.com

The ContextMenu isn't in the same part of the Visual Tree so that's why you can't use ElementName etc. to reference the DataGrid. You'll have to use PlacementTarget of the ContextMenu instead.

WPFXAMLのビジュアルツリーの中に右クリックメニューが含まれてないので、CommandParamterに要素名(ElementName)を指定しても動きませんよ、という話らしい。

DataGridの選択値を取るだけだったら、これで行ける。

<MenuItem Command="{Binding HogeCommand}"
                     CommandParameter="{Binding Path=PlacementTarget.SelectedItems, RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}"
                        Header="TEST"/>

ViewModelではこうやれば取れる。

   System.Collections.IList items = (System.Collections.IList)parameter;

ただ、右クリック→ダイアログ出して再検索→リフレッシュなんかしたい場合、「ダイアログを出す」為にUIElementのオブジェクトが必要になるので、DataGridの選択行のオブジェクトだけでは足りない。処理中ダイアログなど要らない(MessageBoxで上等)であれば、別段問題ないんだけどね。

ただ、どうせXAMLにイベントの情報書くんであれば、右クリックメニューでコードビハインドでクリックイベントを追加しても大差ないと思う... UIのオブジェクトでも選択値でも何でも取れるぞい。