我现在正在学习 MVVM。由于我看到很多教程或项目只使用 View 和 ViewModel,我有点困惑。这是我的代码。
模型 :
public class StudentModel : PropertyChangedBase
{
private String _firstName;
public String FirstName
{
get { return _firstName; }
set
{
_firstName = value;
NotifyOfPropertyChange(() => FirstName);
}
}
private Double _gradePoint;
public Double GradePoint
{
get { return _gradePoint; }
set
{
_gradePoint = value;
NotifyOfPropertyChange(() => GradePoint);
}
}
}
看法 :
<UserControl x:Class="MVVMLearningWithCaliburnMicro.Views.StudentView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:cal="http://www.caliburnproject.org">
<Grid Width="525" Height="300" Background="Lavender">
<DockPanel>
<TextBlock HorizontalAlignment="Center" Text="Student Data"
DockPanel.Dock="Top" FontSize="20" />
<StackPanel Orientation="Vertical" HorizontalAlignment="Center"
VerticalAlignment="Stretch"
Margin="0,8" DockPanel.Dock="Top">
<StackPanel Orientation="Horizontal" Margin="0,5">
<TextBlock Text="Name" FontSize="15" Margin="5,0" />
<TextBox Name="txtName" Text="{Binding Path=Student.FirstName}" Width="250" />
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="0,5">
<TextBlock Text="Grade" FontSize="15" Margin="5,0" />
<TextBox Name="txtGrade" Text="{Binding Path=Student.GradePoint}" Width="250" />
</StackPanel>
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="0,5" HorizontalAlignment="Center"
VerticalAlignment="Bottom"
DockPanel.Dock="Bottom">
<Button Name="btnSave" Width="100" Height="40"
cal:Message.Attach="SaveStudent">
<TextBlock Text="Save" FontSize="15" />
</Button>
</StackPanel>
</DockPanel>
</Grid>
</UserControl>
视图模型:
public class StudentViewModel
{
public StudentModel Student { get; set; }
public void SaveStudent()
{
MessageBox.Show(String.Format("Saved: {0} - ({1})", Student.FirstName, Student.GradePoint));
}
public StudentViewModel()
{
Student = new StudentModel { FirstName = "Tom Johnson", GradePoint = 3.7 };
}
private Boolean CanSaveStudent()
{
return Student.GradePoint >= 0.0 || Student.GradePoint <= 4.0;;
}
}
Q :
1. 我怎么把我的守卫财产NotifyOfPropertyChange()
放在模型里?
2.(愚蠢的问题)我的 MVVM 模式是否指向了正确的方法?