定义视图模型
打开前一个项目
打开RegistrationViewModel.cs文件添加如下属性到RegistrationViewModel类
[POCOViewModel]
public class RegistrationViewModel {
public static RegistrationViewModel Create() {
return ViewModelSource.Create(() => new RegistrationViewModel());
}
protected RegistrationViewModel() {
if(this.IsInDesignMode())
InitializeInDesignMode();
else InitializeInRuntime();
}
void InitializeInDesignMode() {
FirstName = "John";
LastName = "Smith";
Email = "John.Smith@JohnSmithMail.com";
Password = "Password";
ConfirmPassword = "Password";
Birthday = new DateTime(1980, 1, 1);
}
void InitializeInRuntime() {
Birthday = null;
}
public virtual string FirstName { get; set; }
public virtual string LastName { get; set; }
public virtual string Email { get; set; }
public virtual string Password { get; set; }
public virtual string ConfirmPassword { get; set; }
public virtual DateTime? Birthday { get; set; }
}
从RegistrationViewModel是一个POCO类,所有定义属性都是可绑定的
InitializeInRuntime方法初始化生日属性。DateTime结构是一个值类型,因此Birthlday字段可以使用可空DateTime。和一个不可空类型,Birthday字段可能初始化在特定的值,没有被推荐
注册数据
添加AddEmployee方法到视图模型
[POCOViewModel]
public class RegistrationViewModel {
...
public void AddEmployee() {
EmployeesModelHelper.AddNewEmployee(FirstName, LastName, Email, Password, Birthday.Value);
}
}
POCO机制自动生成一个命令对于方法。生成的命令名字如下方法匹配[MethodName]Command。设置Command属性注册按钮:
<dxlc:LayoutControl Orientation="Vertical" ItemStyle="{StaticResource itemStyle}" ItemSpace="10">
...
<Button Content="Register" HorizontalAlignment="Center" VerticalAlignment="Bottom" Width="80"
Command="{Binding AddEmployeeCommand}" />
</dxlc:LayoutControl>
绑定编辑器
重新生成项目
选择First Name TextEdit元素布局内容调用Quick Actions。点击重新排列按钮到EditValue右侧属性选择Create Data Binding
在调用对话框,启动Custom选项输入"FirstName"
绑定创建,FirstName编辑器显示测试数据在vs设计器
绑定余下的编辑器到它们的对应的属性和注册按钮到AddEmployee命令。XAML如下显示结果
<dxlc:LayoutControl Orientation="Vertical" ItemStyle="{StaticResource itemStyle}" ItemSpace="10">
<dxlc:LayoutGroup ItemSpace="10">
<dxlc:LayoutItem Label="Name">
<dxe:TextEdit EditValue="{Binding FirstName}" />
</dxlc:LayoutItem>
<dxe:TextEdit VerticalAlignment="Bottom" EditValue="{Binding LastName}" />
</dxlc:LayoutGroup>
<dxlc:LayoutItem Label="Email">
<dxe:TextEdit EditValue="{Binding Email}" />
</dxlc:LayoutItem>
<dxlc:LayoutItem Label="Create a password">
<dxe:PasswordBoxEdit EditValue="{Binding Password}" />
</dxlc:LayoutItem>
<dxlc:LayoutItem Label="Confirm your password">
<dxe:PasswordBoxEdit EditValue="{Binding ConfirmPassword}" />
</dxlc:LayoutItem>
<dxlc:LayoutItem Label="Birthday">
<dxe:DateEdit EditValue="{Binding Birthday}" />
</dxlc:LayoutItem>
<Button Content="Register" HorizontalAlignment="Center" VerticalAlignment="Bottom" Width="80"
Command="{Binding AddEmployeeCommand}" />
</dxlc:LayoutControl>
编辑器不显示测试数据在运行时