Specify Command for MenuItem in a DataTemplate

arconaut picture arconaut · May 22, 2009 · Viewed 15.9k times · Source

I have a context menu. It's bound to some collection and it has a defined ItemTemplate like this:

<ContextMenu
    ItemsSource={Binding ...}
    ItemTemplate={StaticResource itemTemplate}
    />

itemTemplate is a simple DataTemplate with a TextBlock:

<DataTemplate x:Key="itemTemplate">
    <TextBlock Text={Binding ...} />
</DataTemplate>

How do I bind Command property for MenuItem to the underlying object's property?

Answer

Martin Harris picture Martin Harris · May 22, 2009

I think you need to wrap your TextBlock in a MenuItem:

<DataTemplate x:Key="itemTemplate">
    <MenuItem Command={Binding ...}>
        <TextBlock Text={Binding ...} />
    </MenuItem>
</DataTemplate>

But I don't have an IDE in front of me right now to try this. Let me know how it goes.


Looks like you need to use the ItemContainerStyle as seen here. Sorry for leading you down the wrong path at the start there - but I got in front of an IDE and this works:

<ContextMenu.ItemContainerStyle>
    <Style TargetType="MenuItem">
        <Setter Property="Command" Value="{Binding ...}"/>
    </Style>
</ContextMenu.ItemContainerStyle>