Is it possible to set code behind a resource dictionary in WPF for event handling?

前端 未结 4 1801
孤城傲影
孤城傲影 2020-11-22 10:49

Is it possible to set code behind a resource dictionary in WPF. For example in a usercontrol for a button you declare it in XAML. The event handling code for the button clic

4条回答
  •  不思量自难忘°
    2020-11-22 11:03

    I think what you're asking is you want a code-behind file for a ResourceDictionary. You can totally do this! In fact, you do it the same way as for a Window:

    Say you have a ResourceDictionary called MyResourceDictionary. In your MyResourceDictionary.xaml file, put the x:Class attribute in the root element, like so:

    
    

    Then, create a code behind file called MyResourceDictionary.xaml.cs with the following declaration:

    namespace MyCompany.MyProject
    {
        partial class MyResourceDictionary : ResourceDictionary
        { 
           public MyResourceDictionary()
           {
              InitializeComponent();
           }     
           ... // event handlers ahead..
        }
    }
    

    And you're done. You can put whatever you wish in the code behind: methods, properties and event handlers.

    == Update for Windows 10 apps ==

    And just in case you are playing with UWP there is one more thing to be aware of:

    
    
    
        
            
                
    
                    
                    
    
                    
                    
    
                
            
        
    
    
    

提交回复
热议问题