How to Interact Between ViewModels in WPF and How to Manage Views Lifecycle

There are three windows MainWindow, FirstWindow and SecondWindow. MainWindow can open FirstWindow and SecondWindow.

Now my question is:

  • How to open SecondWindow from FirstWindow and close FirstWindow when opening SecondWindow. At this time, I can control SecondWindow, but I cannot control MainWindow, just like with SecondWindow.ShowDialog () from MainWindow.
  • After I click the "Save" button on SecondWindow, SecondWindow will be closed and the DataGrid from MainWindow will be updated. How to update data from another ViewModel or how to return data when processing an event?
+4
source share
3

.

2 . ( ) . , , MVVM Framework.

-, , , (WPF, UWP, Silverlight ..).

+1

.

( ViewModels) EventAggregator. / . .

CodeProject WeakReference, . , . ISubscriber .

Microsoft Prism. , , . .

- MVVMLight Messenger.

, Singleton .

. - . MVVM- .

- (WPF, Silverlight, WinRT, Xamarin).

, Microsoft Prism RegionManager . , .

MVVM Light .

. , .net Prism.

. , MVVM.

, MVVM-, ( Messenger NavigationService, , PopupService, , INotifyPropertyChanged -helpers ViewModel) .

+1

You need to use an instance of the form class to transfer data. Check out my simple two-form project below.

Form 1

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        Form2 form2;
        public Form1()
        {
            InitializeComponent();
            form2 = new Form2(this);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            form2.Show();
            string  results = form2.GetData();
        }
    }
}

Form 2

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form2 : Form
    {
        Form1 form1;
        public Form2(Form1 nform1)
        {
            InitializeComponent();

            this.FormClosing +=  new FormClosingEventHandler(Form2_FormClosing);
            form1 = nform1;
            form1.Hide();
        }
        private void Form2_FormClosing(object sender, FormClosingEventArgs e)
        {
            //stops form from closing
            e.Cancel = true;
            this.Hide();
        }
        public string GetData()
        {
            return "The quick brown fox jumped over the lazy dog";
        }

    }
}
-1
source

Source: https://habr.com/ru/post/1619772/


All Articles