Search code examples
c#mvvm-lightuwp-xaml

How raise an event in the viewmodel of the actual landing page, when it is triggered from a menu item in the view of the main page?


In both view models, main page and landing page, there are the same methods called 'SaveEntry'. if the menu item is clicked, implemented in the view of main page, in the case, that the main page is active, the method 'SaveEntry' in the main view model has to execute. In the other case, when the landing page is active and I click the menu item in the main view, then the method 'SaveEntry'in the view model landing page has to execute.

The navigation from the main page to the landing page is implemented by a routed event:

MainContentFrame.NavigateToType(typeof(WriteEntryPage), null, navOptions);

How I can implement that?


Solution

  • For your requirement, you could use NavigationView as the navigation to process the page navigate, bind the loaded event with Command then execute SaveEntry in View Model when the page was loaded.

    <interactivity:Interaction.Behaviors>
        <core:EventTriggerBehavior EventName="Loaded">
            <core:InvokeCommandAction Command="{x:Bind ViewModel.ViewLoadedCommand}" />
        </core:EventTriggerBehavior>
    </interactivity:Interaction.Behaviors>
    

    ViewModel

    public class MainViewModel : ViewModelBase
    {
        public RelayCommand ViewLoadedCommand { get; private set; }
        public MainViewModel()
        {
            ViewLoadedCommand = new RelayCommand(SaveEntry);
        }
    
    
        private void SaveEntry()
        {
            // save entry.
        }
    }
    

    I have uploaded the code sample please refer.