MVVM模型-模型之间的关联
本文关键字:模型 关联 MVVM 之间 | 更新日期: 2023-09-27 18:02:20
假设我有以下模型:
class Worker
{
int Id;
string firstname;
string lastname;
}
class Department
{
string title;
string description;
List<Worker> workers;
}
我想在UI上显示部门的标题、描述和listbox内的工人列表(在listbox中我只想显示姓和名)。
我是否需要创建一个视图模型来包装这个关系,或者我必须为我拥有的每个模型创建一个视图模型?
你可以创建一个ViewModel,它把它们都包装起来,像:
namespace XXXX.ViewModel
{
public class MainViewModel : ViewModelBase
{
private int _id;
private string _total;
private string _description;
private ObservableCollection<Worker> _workers;
public int Id
{
get { return _id; }
set
{
if (value == _id) return;
_id = value;
RaisePropertyChanged("Id");
}
}
public string Total
{
get { return _total; }
set
{
if (value == _total) return;
_total = value;
RaisePropertyChanged("Total");
}
}
public string Description
{
get { return _description; }
set
{
if (value == _description) return;
_description = value;
RaisePropertyChanged("Description");
}
}
public ObservableCollection<Worker> Workers
{
get { return _workers; }
set
{
if (value == _workers) return;
_workers = value;
RaisePropertyChanged("Workers");
}
}
//****************** You Logic *************************
public MainViewModel()
{
Department department = new Department();
}
//****************** You Logic *************************
}
}
你不会为每个模型都有ViewModel,在MVVM中你应该为几乎每个视图都有一个唯一的ViewModel。然后将模型映射到ViewModel。
例如: public class DepartmentViewModel
{
public string title { get; set; }
public string description { get; set; }
public IEnumerable<Worker> workers { get; set; }
//Additional ViewModel properties here
//These may or may not be items that exist in your Model
/// <summary>
/// Mapped to the description but truncated to 10 characters and followed by an elispe (...)
/// </summary>
public string ShortDescription
{
get
{
return description.Substring(0,10) + "...";
}
}
}
一开始我意识到这看起来有点多余。但是,您可能会从模型中创建其他非1:1类型的视图。
还可以查看automapper.org,这是一个映射对象到对象的好工具。
您有一个视图模型,其中包含工人和部门。
如果视图只想显示工人的某些属性,那么视图应该进行过滤。尝试使用项目模板:
<ListBox x:Name="_workers" ItemsSource="{Binding Workers}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding firstname}" />
<TextBlock Text=" " />
<TextBlock Text="{Binding lastname}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
视图模型应该包含:
private string _title;
public string Title {
get {return _title;}
set {_title = value; RaisePropertyChanged("Title");}
}
private string _description;
public string Description {
get {return _description;}
set {_description= value; RaisePropertyChanged("Description");}
}
public ObservableCollection Workers {get; private set;}
public Constructor()
{
Workers = new ObservableCollection();
}
//This method is called by the model once it has fetched data.
//This can be done as a callback or in an event handler
public CalledByTheModelAfterLoadingData(Department department)
{
Title = department.Title;
Description = department.Description;
foreach (var worker in department.Workers)
{
Workers.Add(worker);
}
}