Binding ViewModel to multiple windows

后端 未结 4 805
醉话见心
醉话见心 2021-02-14 21:37

I\'m re-writing my windows forms project that does scoring for sheep shearing events (don\'t ask, its a huge sport in New Zealand) from vbnet to wpf c# and have struck a problem

4条回答
  •  -上瘾入骨i
    2021-02-14 22:08

    That's because both windows must share the exact same instance of the ViewModel.

    All your properties are instance properties, like

    public string CurrentEventName { get { // snip
    

    and therefore all values are distinct to each instance. You're creating two instances, one for each window.

    
        
            
        
    

    That's one instance, and here's the other

    
        
            
        
    

    Remember, xaml is just markup that is deserialized into an object graph. You've got two different markup files, they contain distinct instances of everything described within them.

    There's nothing wrong with this, and nothing wrong with having a view model with instance properties. In fact, that's the preferred way over using statics and static bindings.

    The answer is luckily simple. You need to hand both windows the same instance of your view model.

    First, remove all the nonsense from both of your windows. That's not for you. Now, simply change your constructor to

    public MainWindow()
    {
        var viewModel = new SheepViewModel();
        ScoreScreen SW = new ScoreScreen();
        SW.DataContext = viewModel;
        SW.Show();
        InitializeComponent();
        //NOTICE!  After Init is called!
        DataContext = viewModel;
    }
    

    And you're done.

提交回复
热议问题