我有一些按钮的WPF应用程序。一个按钮名为ChangeTime,因此单击该对话框会打开,您可以更改hh / mm / ss。我想将选择的时间存储在变量中。
我的问题是,如果用户确实更改了时间,我只想存储该新时间。当前,当用户按下按钮时,事件触发和新值被存储。同样,在不触摸“时间”字段的情况下关闭对话框时,也不应存储新值。
基本上,我想在实际更改时间时将BtnWasClicked更改为true。变量名称的选择确实很差。
有什么预防方法吗?
private DateTimePicker _timePortionDateTimePicker;
private DateTime _pickedTime;
private bool btnWasClicked = false;
private bool timeChanged = false;
private void TimeIsChanged(object sender, EventArgs e)
{
timeChanged = true;
if (timeChanged)
{
btnWasClicked = true;
}
}
private void BtnChangeTime_OnClick(object sender, EventArgs e)
{
Form timeDialog = new Form();
_timePortionDateTimePicker = new DateTimePicker();
_timePortionDateTimePicker.Format = DateTimePickerFormat.Time;
_timePortionDateTimePicker.ShowUpDown = true;
_timePortionDateTimePicker.ValueChanged += new
EventHandler(TimeIsChanged);
timeDialog.Controls.Add(_timePortionDateTimePicker);
timeDialog.ShowDialog();
_pickedTime = _timePortionDateTimePicker.Value;
}
答案 0 :(得分:1)
您实际上并不需要TimeIsChanged
。您只需检查_timePortionDateTimePicker.Value
与_pickedTime
中的BtnChangeTime_OnClick
是否不同。
Form timeDialog = new Form();
_timePortionDateTimePicker = new DateTimePicker();
_timePortionDateTimePicker.Format = DateTimePickerFormat.Time;
_timePortionDateTimePicker.ShowUpDown = true;
// start with the previous chosen time
_timePortionDateTimePicker.Value = _pickedTime;
timeDialog.Controls.Add(_timePortionDateTimePicker);
timeDialog.ShowDialog();
if (_pickedTime != _timePortionDateTimePicker.Value) {
// time has changed, assign to _pickedTime and other variables
_pickedTime != _timePortionDateTimePicker.Value;
timeChanged = true;
btnWasClicked = true;
} // otherwise do nothing