MenuItem をデータバインディングで作る。
最近 MVVM を勉強がてら WPF を触ってる。
で、コンテキスト メニューをデータバインディングで作ろうと思ったらはまったのでメモ。
課題
WPF で MVVM やってるときに MenuItem をデータバインディングで作りたいって思うことあると思うんです。
で、こうやるとうまくいかない。
<ContextMenu ItemsSource="{Binding Path=SomeCollection}"> <ContextMenu.ItemTemplate> <DataTemplate> <MenuItem Header="{Binding Path=DisplayName}" Command="{Binding Path=Command}" /> </DataTemplate> </ContextMenu.ItemTemplate> </ContextMenu>
メニューが重なっちゃう。
DataTemplate 内で MenuItem を使っちゃダメらしい。
解決方法
解決方法は stackoverflow にあった。
ItemTemplate を使わない。ItemContainerStyle を使う。
具体的にはこんな感じ。
<ContextMenu ItemsSource="{Binding Path=SomeCollection}"> <ContextMenu.ItemContainerStyle> <Style TargetType="MenuItem"> <Setter Property="Header" Value="{Binding Path=DisplayName}"/> <Setter Property="Command" Value="{Binding Path=Command}"/> </Style> </ContextMenu.ItemContainerStyle> </ContextMenu>
これで OK。