一、MVVM模式的大致架构如下图:
二、对应例子阐述上图:
View层与ViewModel层交互:
1、属性绑定:将ViewModel层的Name属性绑定到View层的Textbox上
<TextBox Height="23" HorizontalAlignment="Left" Text="{Binding Name,Mode=TwoWay}" DataContext="{StaticResource vm}" Margin="79,32,0,0" x:Name="tbName" VerticalAlignment="Top" Width="120" />
2、UI事件通知(触发器)
<Button Content="Go" Height="23" HorizontalAlignment="Left" Margin="305,244,0,0" x:Name="button1" VerticalAlignment="Top" Width="75" >
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<ei:CallMethodAction TargetObject="{StaticResource vm}" MethodName="Auth" />
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
点击View层的Button时,触发调用ViewModel层的Auth方法
ViewModel与Model层交互
1、 Model层为ViewModel层提供基础实体的属性
public string Name
{
get { return name; }
set
{
name = value;
}
}
2、ViewModel层对Model实体进行验证调用
public string Name
{
get { return name; }
set
{
this.errors.Remove("Name");
if (value == null || value.Length > 15 || value.Length < 6)
{
errors.Add("Name", "名字为6到15位");
}
name = value;
ErrorNotify("Name");
}
}
验证存放在name的value值是否为6到15位