How to obtain feedback from an event?
I wonder how to obtain feedback from an event?
Situation:
Let's say that a object (Slave
) can produce events(request changing a property). An other object (Master
) subscribes to these events, analyzes the changing property value and accepts, or denies this change. Then the feedback is returned to the Slave
, and it change or not its property.
Example:
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;
}
}
}
[EDIT]
With your suggestions some modifications in the code am I sure that Cancel
is already updated?
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;
}
}
}
Use a custom EventArgs type that contains the feedback.
CancelEventArgs is an example of such an implementation, where the subscriber can set the Cancel property.
You declare your own class and pass an instance of it instead of "EventArgs.Empty".
The event hander changes properties on the event object (providing feedback).
You then check the event args object and check the feedback provided.
Any questions?
e.g.
class FeedbackEventArgs: EventArgs
{
public bool IsOk {get; set;}
}
...
FeedbackEventArgs feedback = new FeedbackEventArgs();
feedback.IsOK = false;
if (!DateChanging == null)
DateChanging(this, feedback);
if (feedback.IsOK)
精彩评论