Updating UI objects in windows forms
Pre .net I was using MFC, ON_UPDATE_COMMAND_UI, and the CCmdUI class to update the state of my windows UI. From the older MFC/Win32 reference:
Typically, menu items and toolbar buttons have more than one state. For example, a menu item is grayed (dimmed) if it is unavailable in the present context. Menu items can also be checked or unchecked. A toolbar button can also be disabled if unavailable, or it can be checked.
Who updates the state of these items as program conditions change? Logically, if a menu item generates a command that is handled by, say, a document, it makes sense to have the document update the menu item. The document probably contains the information on which the update is based.
If a command has multiple user-interface objects (perhaps a menu item and a toolbar button), both are routed to the same handler function. This encapsulates your user-interface update code for all of the equivalent user-interface objects in a single place.
The framework provides a convenient interface for automatically updating user-interface objects. You can choose to do the updating in some other way, but the interface provided is efficient and easy to use.
What is the guidance for .net Windows Forms? I am using an Application.Idle handler in the main form but am not sure this is the best way t开发者_JAVA百科o do this. About the time I put all my UI updates in the Idle event handler my app started to show some performance problems, and I don't have the metrics to track this down yet. Not sure if it's related.
I've found it easiest to have the menu item event handler spawn a background thread that disables the menu item, does the work, and then re-enables the menu item. That way, the UI is available to handle other UI requests, and I don't need to poll for when the operation is complete.
I usually include logic that prevents more than one operation that uses the same resources to happen simultaneously. This means creating a function to disable/enable all similar resources at once. e.g. I might only allow 1 file operation to happen at a time, so I would create a function to disable/enable all the menu items associated with file operations and call it from every one of those menu items.
Just change their property, e.g.
obj.Enabled = true;
or
obj.Enabled = false;
The property of that object will automatically call .Invalidate()
or .Refresh()
for you, so the control should be repainted automatically.
If you want to do a BIG task which would block the UI for multiple seconds, it's worth using Threads + Delegates.
AFAIK, in the standard .NET System.Windows.Forms world, this functionality is not available out the box. This problem can be answered in a few ways. The links below are useful resources:
•OnUpdate equivalent
•ActionLists for Windows forms
•Command UI Updating Windows Forms in C#
精彩评论