How to transfer the values of the string variable from Page1 to Page2 using MVVM?
1 answer
Eh. Well, let's chew.
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; }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.In the VM part, you must create
MainVMand 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; } }Now View. You should not try to install a
DataContextfrom a View in MVVM; this is not within the competence of the View. When you create a View, immediately hang the desiredDataContext:var p1 = new Page1() { DataContext = mainVM.P1VM }; var p2 = new Page2() { DataContext = mainVM.P2VM };Inside
Page1do aBindingon 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
|
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