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>

メニューが重なっちゃう。

f:id:kei10in:20111126005910p:image


DataTemplate 内で MenuItem を使っちゃダメらしい。


ContextMenuへのバインディング(2of3)

解決方法

解決方法は stackoverflow にあった。

http://stackoverflow.com/questions/1312895/using-a-datatemplate-for-a-menuitem-causes-extra-space-on-the-left-side-to-appea


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。