Help, I Have No Style!

I'm blogging to:

The Beastie Boys
To The 5 Burroughs

Okay, I'm not talking about me personally...although I guess that is debatable.  But most folks who know me would most likely tell you that I certainly have some kind of style, but opinions may differ about the quality of that style :)  And I do have to tell you that back in the 70s (yes, the 70s) I owned several polyester leisure suits and platform shoes.  But alas, that stuff is like my waist line...long gone.

Then what *am* I talking about?  I'm specifically talking about using Windows Forms controls in a WPF application and noticing that your controls are not appropriately styled.  Let's take a look at an example.  Suppose we want to use a System.Windows.Forms.TabControl in a WPF application.  We'll use code to do this today...

private void WindowLoaded(object sender, RoutedEventArgs e)
{
     WindowsFormsHost host = new WindowsFormsHost();
System.Windows.Forms.TabControl tc = new System.Windows.Forms.TabControl();
tc.TabPages.Add("Tab1");
tc.TabPages.Add("Tab2");
host.Children.Add(tc);
     this.grid1.Children.Add(host);
}

This of course assumes that we have the following XAML...

<

Window x:Class="AvalonApplication25.Window1"
     xmlns=https://schemas.microsoft.com/winfx/avalon/2005
     xmlns:x=https://schemas.microsoft.com/winfx/xaml/2005
     Title="AvalonApplication25"
     Loaded="WindowLoaded"
     >

<

Grid x:Name="grid1">
</Grid>
</Window>

Give 'er a spin and let's see what happens...

 

Hm, not exactly what we were expecting.  We want this tab control to look like it looks when you use a standard Windows Forms application and this does not look the same.  What's different?  Well, a normal WF application by default enables visual styles which will style our controls appropriately.  But for some reason, that does not seem to happen when we are hosting controls in a WPF application.  Let's see why...

If examine a typical WF applicaiton, we notice that in the Main method of the application (in the Program.cs file) there is a call to:

Application.EnableVisualStyles();

We don't have the same situation in a WPF application since the application template is not generating this line of code anywhere.  So we just have to make sure we do it manually.  So all we have to do is modify our code to explicitly call this method:

private void WindowLoaded(object sender, RoutedEventArgs e)
{

System.Windows.Forms.

Application.EnableVisualStyles(); // <--- Add this line

     WindowsFormsHost host = new WindowsFormsHost();
System.Windows.Forms.TabControl tc = new System.Windows.Forms.TabControl();
tc.TabPages.Add("Tab1");
tc.TabPages.Add("Tab2");
host.Children.Add(tc);
     this.grid1.Children.Add(host);
}

Now let's run it again...

 

Ah, now that looks much better, huh?