VSTO: Enable ribbon button only when a document is loaded



  • How does one set a ribbon button in a Word add-in to be enabled when a document is loaded and disabled when no documents are loaded, just Like most of the built-in buttons?

    Can one bind a global flag to the "Enabled" property of the button, or is it more complicated than that? I know I could create a timed loop that checks for changes in Application.Documents, but I'm looking for something "cleaner" if possible.

    I've already looked at Disable Own Word 2007 Add-In If No Document Loaded and other related questions.

    There are several ways to handle this.

    first, you can create a publicly exposed function that returns true or false for the enabled state of your button (however you want to determine that), you then define your ribbon xml to point to that function for the Enabled property getter. If you're dealing with an IExtensibility based addin, then this is the way you'd have to go.

    If you're dealing with VSTO, then define your ribbon button in the ribbon designer and make it DISABLED by default.

    Then, during the STARTUP event, hook the WORD object, specifically the NEWDOCUMENT, DOCUMENTOPEN and WINDOWACTIVATE events.

    In the event handler code for each of those events, enable or disable your buttons as applicable depending on which event fired and which document was activated at the time.

    Mike Fuchs

    Use the DocumentChange event instead. Hook up will be something like this:

    Globals.ThisAddIn.Application.DocumentChange += new EventHandler(OnDocumentChange);
    
    

    And the Handler

    void OnDocumentChange()
    {
        this.myButton.Enabled = wordApp.Documents.Count > 0;
    }
    
    

    Interesting, my VSTO Contrib project (http://vstocontrib.codeplex.com/documentation) has some features which make ribbon management simpler.

    The cleanest way is to use my ribbon factory, but the project will need to be updated to disable buttons if there are no viewmodels to query for the status of the button. In fact it is a scenario I havent really covered.

    You have 3 parts an add-in is interested in, the view (window), the context (the document) and the ribbon. VSTO Contrib means you get a view model per context, and it manages/abstracts the ribbon and view so it appears you have a ribbon per context, and it tells you the current active view (for multiple windows showing same document scenarios). The missing part is if there is a ribbon, but no contexts and no viewmodels, it should invalidate that ribbon control and disable it. It should be a pretty simple change, email me if you are interested in giving VSTO Contrib's RibbonFactory a spin and I can make this change for you.

    来自:https://stackoverflow.com/questions/6399111/vsto-enable-ribbon-button-only-when-a-document-is-loaded



最新帖子

推荐阅读