MVVM视图模型到一个视图



我在这里使用MVVM。我有一个模型Patient.cs和三个视图模型ViewModel1ViewModel2ViewModel3。我现在必须将3个视图模型转换为一个模型。

有人能告诉我最好的方法吗?下面是我的代码:

ViewModel1.cs

public class ViewModel1 {
[Required]
public string? YearOfBirth { get; set; }
[Required]
public string? DriversLicenseId { get; set; }

}

ViewModel2.cs

public class ViewModel2
{
[Required]
[StringLength(16, ErrorMessage = "First name should be 16 character or less.")]
public string? FirstName { get; set; }

[Required]
[StringLength(16, ErrorMessage = "Last name should be 16 character or less.")]
public string? LastName { get; set; }

[Required]
public DateTime? DateOfBirth { get; set; } 

}

ViewModel3.cs

public class ViewModel3
{
[Required]
public string? Address1 { get; set; }
[Required]
public string? City { get; set; }
[Required]
public string? State { get; set; }
[Required]
public string? ZipCode { get; set; }    


}

型号Patient.cs

public class Patient 
{
public string? FirstName { get; set; }
public string? LastName { get; set; }
public DateTime? DateOfBirth { get; set; }
public Gender? Gender { get; set; }
public string? YearOfBirth { get; set; }
public string? DriversLicenseId { get; set; }
public string? Address1 { get; set; }
public string? City { get; set; }
public string? State { get; set; }
public string? ZipCode { get; set; } 
public string? PaymentType { get; set; }
}

我正在寻找将所有三种视图模型转换为Patient.cs 的方法

谢谢。

在我看来,您需要明确地进行此类业务。如果在3个独立的视图模型中保持Model字段的碎片对您来说很重要,那么如果是我,我会创建一种类型的超级视图模型,其中包含3 ViewModel1,2,3的实例,并将您的视图上下文绑定到该超级视图模型的实例。您可以将视图中的字段绑定到它们各自的属性,在属性前加上ViewModel1.ViewModel2ViewModel3。例如,将您的"名字"文本字段绑定到属性ViewModel1.FirstName。然后,您可以创建Patient模型类的实例并显式设置字段(请参阅SavePatientRecord过程(类似于以下内容。。。

public class SuperViewModel 
{
private ViewModel1 _viewModel1;
private ViewModel2 _viewModel2;
private ViewModel3 _viewModel3;
public ViewModel1 ViewModel1
{
get
{
return _viewModel1;
}
set
{
_viewModel1 = value;
}
}
public ViewModel2 ViewModel2
{
get
{
return _viewModel2;
}
set
{
_viewModel2 = value;
}
}

public ViewModel3 ViewModel3
{
get
{
return _viewModel3;
}
set
{
_viewModel3 = value;
}
}

public SuperViewModel()
{
_viewModel1 = new ViewModel1();
_viewModel2 = new ViewModel2();
_viewModel3 = new ViewModel3();
}
public ICommand SavePatientRecord()
{
Patient patient = new Patient();
patient.YearOfBirth = ViewModel1.YearOfBirth;
patient.DrivesLicenceId = ViewModel1.DrivesLicenceId;

patient.FirstName = ViewModel2.FirstName;
patient.LastName = ViewModel2.LastName;
patient.DateOfBirth = ViewModel2.DateOfBirth;
patient.Address1 = ViewModel3.Address1;
patient.City = ViewModel3.City;
//
// etc.
// etc.
//
}
}

您不需要重复variables

Patient.cs

public class Patient 
{
// Constructor
public Patient()
{
_viewModel1 = new ViewModel1();
_viewModel2 = new ViewModel2();
_viewModel3 = new ViewModel3();
}
public ViewModel1 _viewModel1 { get; set; }
public ViewModel2 _viewModel2 { get; set; }
public ViewModel3 _viewModel3 { get; set; }
}

相关内容

  • 没有找到相关文章