How to transfer the values ​​of the string variable from Page1 to Page2 using MVVM?

  • 2
    Put it in a shared VM. </ thread> - VladD
  • I need to give the value to a variable in Page1, and transfer this value to Page2. Suppose I have a common VM - string Pas . What am I doing in Page1VM, and what is in Page2VM? I've done this in the Page1VM constructor: Page1VM text = new Page1Vm(); text.Pas = this.Pass ... if I understood correctly, of course ... and what to do in Page2VM? - Alexander Kasikov
  • If it is necessary to permanently share one, then there must be a common class. If you transmit at some moments - events may come up. - Monk
  • So you mean that in a separate class there will be `public string Pas {get; set; } and all? I’m just getting to know MVVM, and all these Binding, ViewModel I’m talking recently, so I’m asking for a specific example so that I can understand it - Alexander Kasikov
  • one
    It depends on how the two pages are logically linked. VMs are usually created according to some analogies in the ordinary world. - Monk

1 answer 1

Eh. Well, let's chew.

  1. We get the general part of the data in the form of separate VM:

     public class CommonVM : INotifyPropertyChanged { string pas; public string Pas { get { return pas; } set { if (pas != value) { pas = value; NotifyPropertyChanged(); } } } void NotifyPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public event PropertyChangedEventHandler PropertyChanged; } 
  2. We get on VM for each page:

     class P1VM : INotifyPropertyChanged { public P1VM(CommonVM commonVM) { CommonVM = commonVM; } public CommonVM CommonVM { get; private set; } // и не забудьте реализовать INotifyPropertyChanged } 

    and the same Page2VM .

  3. In the VM part, you must create MainVM and have internal VMs in it:

     public class MainVM { public MainVM() { var commonVM = new CommonVM(); P1VM = new P1VM(commonVM); P2VM = new P2VM(commonVM); } public P1VM P1VM { get; private set; } public P2VM P2VM { get; private set; } } 
  4. Now View. You should not try to install a DataContext from a View in MVVM; this is not within the competence of the View. When you create a View, immediately hang the desired DataContext :

     var p1 = new Page1() { DataContext = mainVM.P1VM }; var p2 = new Page2() { DataContext = mainVM.P2VM }; 
  5. Inside Page1 do a Binding on the desired property:

     <TextBox Text="{Binding CommonVM.Pas}"/> 

Look like that's it.

  • If it is exactly stated in the header page1 -> page2, then it was possible to get around p1vm -> p2vm, with unidirectional dependency. But in general - yes, it looks logical and convenient. If the author described the entity, it would be easier to understand what he needs. - Monk
  • @Monk: I am for “growth” reasons, yes. - VladD