Search code examples
c#wpfxamldata-bindingribbon-control

RibbonMenuButton Binding item clicked to command


I have a problem with the RibbonMenuButton. Currently I have :

<RibbonMenuButton Label="Meeting" Width="Auto" ToolTipDescription="Display requests on the agenda for the meeting selected" ToolTipTitle="Meeting" 
                                  LargeImageSource="pack://application:,,,/Resources/meeting.png"
                                  ItemsSource="{Binding MeetingsAvailable}">                       

    <RibbonMenuButton.ItemTemplate>                            
        <DataTemplate>
            <TextBlock Text="{Binding Value}"/>
        </DataTemplate>
    </RibbonMenuButton.ItemTemplate>                                         
</RibbonMenuButton>

My MeetingsAvailable is actually a Dictionary<int, string>. This code is working, the RibbonMenuButtonis well displaying each Value of the dictionnary.

Now I'm trying to get back the Key of the MenuItem which has been clicked. My idea was to use a ICommand in my ViewModel and to bind an event to this command. But I don't really know how to get the event corresponding to clicking an Item in the RibbonMenuButton

Do someone have already did that ?

Thank you in advance.


Solution

  • You can data bind an ICommand to a RibbonMenuButton using the ItemContainerStyle property, like this:

    <RibbonMenuButton Label="Meeting" ItemsSource="{Binding MeetingsAvailable}" ... >
        <RibbonMenuButton.ItemTemplate>                            
            <DataTemplate>
                <TextBlock Text="{Binding Value}"/>
            </DataTemplate>
        </RibbonMenuButton.ItemTemplate>
        <RibbonMenuButton.ItemContainerStyle>
            <Style TargetType="{x:Type MenuItem}">
                <Setter Property="Command" Value="{Binding DataContext.NameOfCommand,
                    RelativeSource={RelativeSource AncestorType={x:Type Views:View}}}" />
                <Setter Property="CommandParameter" Value="{Binding Key}" />
            </Style>
        </RibbonMenuButton.ItemContainerStyle>                                         
    </RibbonMenuButton>