Search code examples
c#wpfxamltabstabitem

How to apply Control resource on a Control using code


I have created a Control resource for a TabItem in the XAML file. I an generating TabItems dynamically and i want to apply that Control Resource to each and every TabItem that gets generated .How to apply that control resource to every other TabItem using c# code as soon as they are generated.


Solution

  • What I've done is in my C# Code of the class definition, I hooked into the "Loaded" event. From that, I try to find the resource of the style and apply if found... something like

    public class MyTabItem : TabItem
    {
       public MyTabItem()
       {
          Loaded += MyLoadedExtras;
       }
    
       private void MyLoadedExtras( object sender, EventArgs e )
       {
          object basis = TryFindResource("XKeyValueFromYourTabItemStyle");
          if (basis != null)
             Style = (Style)basis;
    
          // disconnect from loaded event after our one time in
          Loaded -= MyLoadedExtras;
       }
    }
    

    So, when you dynamically add an instance of the "MyTabItem", it will immediately look for itself for the resources available and set the style for you.