What is the difference between TreeNode.EndEdit
and setting NodeLab开发者_JAVA技巧elEditEventArgs.CancelEdit
?
Well, on the surface, calling EndEdit(true)
indeed appears to do the same thing as issuing e.CancelEdit = true
in an AfterLabelEdit or BeforeLabelEdit event handler. However, the two approaches are not equivalent, and are not used for the same purpose.
Best to demonstrate with an actual behavior example:
They do the same thing, because:
- If you call
EndEdit(true)
, the tree node will leave edit mode and discard changes, - If you issue
e.CancelEdit = true
duringAfterLabelEdit
, the tree node will leave edit mode and discard changes.
But they're not equivalent, because:
- If you don't call
EndEdit(true)
, the tree node edit mode will not change (obviously), - If you don't issue
e.CancelEdit = true
duringAfterLabelEdit
, the tree node will still leave edit mode (and commit changes), - If you don't issue
e.CancelEdit = true
duringBeforeLabelEdit
, the tree node will still enter edit mode.
Another difference is that EndEdit()
triggers AfterLabelEdit
, but AfterLabelEdit
doesn't recursively trigger itself (fortunately).
Now, usually NodeLabelEditEventArgs.CancelEdit is used for validation, i.e. to discard invalid modifications to the tree node label (during AfterLabelEdit
) or to completely prevent the user from editing the labels of some nodes (during BeforeLabelEdit
). In both cases, the user has either already finished or has not yet started editing the label.
EndEdit() is supposed to be used to forcibly commit or cancel editing while the user is still editing the label. Of course, that means EndEdit(false)
is evil and wrong, because it commits a potentially breaking change before the user has finished typing and without his consent. So, I've never seen it called that way, actually.
Calling EndEdit(true)
to discard the current edit might be useful if something else absolutely requires the focus right now and you don't want to autocommit the incomplete edit when the tree node loses focus. Throwing away your user's work that way is still rude, though.
Back in the MFC days, there was a legitimate use for the EndEdit(true)
equivalent: cancel editing when the user pressed the ESC
key. Believe it or not, that feature wasn't supported out of the box in MFC at that time (and maybe still isn't today, I didn't check).
But nowadays, there's not much use left for EndEdit()
in my opinion. Better let it rest in peace.
精彩评论