prismprism-7

How can I update my ribbon with context items based on the selected view and view model?


In my Prism application, I have a ribbon which I want to be able to update with context commands based on the currently active view and view model. I have my ribbon updating with context commands when a view is opened initially (in OnNavigatedTo), but I can't figure out how to update my ribbon as the user clicks between items in my tab control.

I'm planning on using Prism's IEventAggregator to send an "active view changed" event when the user clicks on a new tab, and then have each view model subscribe to that event and have the view model update the ribbon if the active tab item is that view model's tab. The problem is that I need my event data to include some parameters that specify what the active tab contains, but I don't know how to determine which view model is linked the active tab control item.

How do I know what view model corresponds to a tab control item, or is there another way of solving this problem?


Solution

  • You can just let the view model of the selected tab do the work, no need to over-complicate things:

    xaml:

    <TabControl SelectionChanged="OnSelectionChanged"/>
    

    code-behind:

    private void OnSelectionChanged( object sender, SelectionChangedEventArgs e ) => (((sender as TabControl)?.SelectedContent as FrameworkElement)?.DataContext as IRibbonAwareViewModel)?.OnSelected();
    

    interface implemented by the tab's view model:

    internal interface IRibbonAwareViewModel
    {
        void OnSelected(); // <-- here the view model updates the ribbon
    }