Setting DataContext to multiple sources while respecting MVMM

I have read the other questions regarding a matter similar to this, but it dosn't quite ask for a solution to this simple scenario:

namespace View
{
    /// <summary>
    /// Interaction logic for PuzzleSelectionScreen.xaml
    /// </summary>
    public partial class PuzzleSelectionScreen : Page
    {
        public PuzzleSelectionScreen(PuzzleControllerVM puzzleControllerVM, ScreenSwitcher screenSwitcher)
        {
            InitializeComponent();

            // My button needs a command in screenSwitcher (View) to change Page ..
            // .. with a Property (puzzle data) from puzzleControllerVM (View Model)
            this.DataContext = puzzleControllerVM;
            this.DataContext = screenSwitcher;
        }
    }
}

I can stick screenSwitcher in puzzleControllerVM and access all the properties just by this.DataContext = puzzleControllerVM;, but this would violate MVMM as screenSwitcher contains many View objects.

What I do above, the DataContext will assign to screenSwitcher only because it is executed last, but I want a convenient solution so my DataContext will have access to both sources without having to stick my screenSwitcher in my view model class PuzzleControllerVM.

1 answer

  • answered 2020-05-22 13:35 neelesh bodgal

    U can create a new type which hold reference to both and set the datacontext to the instance of the type.

    Something like this

        public PuzzleSelectionScreen(PuzzleControllerVM puzzleControllerVM, ScreenSwitcher screenSwitcher)
        {
            InitializeComponent();
            this.DataContext = new Hybrid { PuzzleControllerVM = puzzleControllerVM, ScreenSwitcher = screenSwitcher };
        }
    
        public class Hybrid
        {
           public PuzzleControllerVM PuzzleControllerVM { get; set; }
           public ScreenSwitcher ScreenSwitcher { get; set; }
        }