Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specify Command for MenuItem in a DataTemplate

Tags:

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?

like image 758
arconaut Avatar asked May 22 '09 16:05

arconaut


1 Answers

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>
like image 125
Martin Harris Avatar answered Jan 03 '23 04:01

Martin Harris