在尊重MVMM的同时将DataContext设置为多个源

问题描述 投票:0回答:1

我已经阅读了与此类似的其他问题,但并没有完全解决这种简单情况:

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;
        }
    }
}

我可以将screenSwitcher粘贴在puzzleControllerVM中,并仅通过this.DataContext = puzzleControllerVM;访问所有属性,但这会违反MVMM,因为screenSwitcher包含许多View对象。

我在上面的操作中,DataContext仅会在最后执行后才分配给screenSwitcher,但是我想要一个方便的解决方案,因此我的DataContext可以访问两个源,而不必在我的视图中粘贴我的screenSwitcher模型类别PuzzleControllerVM

c# wpf data-binding datacontext
1个回答
0
投票

U可以创建一个新的类型,该类型保留对两者的引用,并将datacontext设置为该类型的实例。

这样的东西

    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; }
    }
© www.soinside.com 2019 - 2024. All rights reserved.