我刚刚开始学习MVVM。告诉我View,Model和ViewModel应该包含什么。
程序显示一个计时器,它也是一个输入字段。如果您在其中输入0到72000之间的数值并更改字段的焦点,则输入的值将转换为hh / mm / ss格式,然后开始倒计时。
一切都放在正确的地方了吗?尚不清楚应在何处实现此功能:
查看
此处已连接DataContext
<Window.DataContext>
<viewmodel:MainViewModel/>
</Window.DataContext>
<Grid Margin="0,0,3.6,5.2">
<TextBox Name="textTimeTop"
GotKeyboardFocus="TextBoxGotKeyboardFocus"
LostKeyboardFocus="TextBoxLostKeyboardFocus"
Text="{Binding Seconds, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}"/>
<Button Content="Change Focus" Click="ButtonChangeFocus"/>
</Grid>
模型
计时器
class TestTimer
{
private DispatcherTimer Timer;
public void StartTimer()
{
Timer = new DispatcherTimer();
Timer.Interval = new TimeSpan(0, 0, 1);
Timer.Tick += Timer_Tick;
Timer.Start();
}
private void Timer_Tick(object sender, EventArgs e)
{
}
}
ViewModel
此处声明的字段和属性
// Removed code for hours and minutes
class MainViewModel : INotifyPropertyChanged
{
private int _userInputSeconds;
public int UserInputSeconds
{
get { return _userInputSeconds; }
set
{
if (_userInputSeconds < 0 || _userInputSeconds > 72000)
throw new ArgumentException("Wrong data, allows only 0..72000");
_userInputSeconds = value;
}
}
private int _seconds;
public int Seconds
{
get { return _seconds; }
set
{
_seconds = value;
OnPropertyChanged("Seconds");
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName]string prop = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(prop));
}
}