Propertygrid changes not picked up when using menu shortcut for saving
I am trying to implement a simple wi开发者_运维知识库ndows forms application, where the user can edit instances of a simple Person class. The application makes use of the standard propertygrid, assigning instances of the Person class to the SelectedObject property of the propertygrid. When the user clicks the menu item Save, the application gets the selected item from the propertygrid and saves it. This works fine.
However, if a shortcut such as ctrl+S, assigned to the menu item, is used for saving the SelectedObject of the propertygrid, then the changes are not picked up. It appears to be related to the fact that the properties of the Person object are not updated unless the field in the propertygrid looses focus, and the ctrl+S shortcut doesn’t take away focus from fields in the propertygrid.
Other developers, such as Mark Gilbert, have solved this issue by forcing away focus from the propertygrid, but this seems to be a bit of a hack, especially since it would be nice to keep the focus at the field. The Visual Studio developers apparently got it right, but I haven’t figured out how.
You have 2 different approaches:
As Mark Gilbert and @Tergiver explain, you can remove the focus from the inplace control which will commit the value change before the menu command is triggered. Since you have to do this from your OnSave handler, you put a dependency on the grid from there.
You can also do the contrary. Derive from the PropertyGrid and override the ProcessCmdKey. If you detect a Ctrl+S, change the focus to the grid itself then call base.ProcessCmdKey(). Contrarily to point 1, this puts a dependency on the shortcut keys of the application (Ctrl+S at least) from the grid. I should add that I didn't try this method but in theory it should work.
Your choice...
Call Focus on the PropertyGrid itself. This ends edit mode and updates the selected object(s), but the selected property doesn't change.
精彩评论