我想知道如何从活动中获得反馈?
情况:
假设一个对象 ( Slave
) 可以产生事件(请求更改属性)。另一个对象 ( Master
) 订阅这些事件,分析更改的属性值并接受或拒绝此更改。然后反馈返回给Slave
,它改变或不改变它的属性。
例子:
public class DateChangingEventArgs : EventArgs {
public DateTime oldDateTime, newDateTime;
DateChangingEventArgs(DateTime oldDateTime,
DateTime newDateTime) {
this.oldDateTime = oldDateTime;
this.newDateTime = newDateTime;
}
}
public class MyDateTextBox : TextBox {
public event EventHandler<DateChangingEventArgs> DateChanging;
public DateTime MyDate;
private DateTime myTempDate;
protected override void OnKeyDown(KeyEventArgs e) {
base.OnKeyDown(e);
if (e.KeyCode == Keys.Enter &&
DateTime.TryParseExact(this.Text, "dd/mm/yyyy",
CultureInfo.InvariantCulture, DateTimeStyles.None,
out myTempDate)) {
if (!DateChanging == null)
DateChanging(this,
new DateChangingEventArgs(MyDate, myTempDate));
if (feedbackOK) // here ????????
MyDate = myTempDate;
}
}
}
[编辑]
根据您的建议,我确定对代码进行了一些修改Cancel
吗?
public class DateChangingEventArgs : CancelEventArgs
...
public class MyDateTextBox : TextBox
{
public event EventHandler<DateChangingEventArgs> DateChanging;
...
protected override void OnKeyDown(KeyEventArgs e) {
if (...)
{
DateChangingEventArgs myRequest;
if (!DateChanging == null) {
myRequest = new DateChangingEventArgs(MyDate, myTempDate);
DateChanging(this, myRequest);
}
// Sure that this value is already updated ??
if (!myRequest.Cancel)
MyDate = myTempDate;
}
}
}