Access view menu object in view model.

Oct 30, 2013 at 2:12 PM
hi,

I have a typical requirement. I am using MVVM light for my development. I have a menu on view and i need to access this object in viewmodel to perform some operations.

Can any one suggest a way to pass menu object from view to viewmodel.


Thanks in advance.
Oct 30, 2013 at 4:00 PM
Hi,

You shouldn't really pass controls to your VM, if possible you should bind to properties, collections etc and use templates in your view.

If you really needed to pass the control to your viewmodel I'd maybe use a relaycommand.

I had to do this once thanks to a control that wasn't MVVM friendly:

View
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="Loaded">
            <mvvm:EventToCommand Command="{Binding commandCarouselInit}" CommandParameter="{Binding ElementName=carousel_personview}" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
ViewModel
public PreviewViewModel()
        {

            // Register to listen for framework and shell messages
            this.commandCarouselInit = new RelayCommand<object>((s) => CarouselSetup(s as Carousel));
        }
If your just want to trigger events in your WM from your context menu you can do something like this (this sample uses Telerik RadContextMenu)
                      <telerik:RadContextMenu.ContextMenu>
                            <telerik:RadContextMenu InheritDataContext="True">
                                <telerik:RadMenuItem Header="Add To favourites"
                                                        Command='{Binding commandAddFav}' 
                                                        CommandParameter='{Binding Menu.UIElement.SelectedItem, RelativeSource={RelativeSource Self}}' >
                                    <telerik:RadMenuItem.IconTemplate>
                                        <DataTemplate>
                                            <Image Source="{StaticResource modulehistory_addfavourite" />
                                        </DataTemplate>
                                    </telerik:RadMenuItem.IconTemplate>
                                </telerik:RadMenuItem>
                            </telerik:RadContextMenu>
                        </telerik:RadContextMenu.ContextMenu>

                       this.commandAddFav = new RelayCommand<object>((s) => { if (s != null) { AddToFavourites(s as ModuleHistory); } });