First I show you what I have and than I explain my problem.
I have a code where I can switch between styles depending on the property "Layout", which can be "Layout1" or "Layout2".
<Grid>
<ContentControl Style="{Binding Layout}">
</ContentControl>
</Grid>
Here are the Style definitions:
<Style x:Key="Layout1" TargetType="{x:Type ContentControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ContentControl}">
.....
<ContentControl Style="{StaticResource myWindow}">
</ContentControl>
.....
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="Layout2" TargetType="{x:Type ContentControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ContentControl}">
.....
<ContentControl Style="{StaticResource myWindow}">
</ContentControl>
.....
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
Each Style use the static ressource "myWindow". In myWindow is a class myControl and myControl use a WindowsFormsControl myControl5.
<Style x:Key="myWindow" TargetType="{x:Type ContentControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ContentControl}">
<Grid >
<local:myControl Margin="0,0,0,0"
</local:myControl>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style TargetType="{x:Type local:myControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:myControl}">
<WindowsFormsHost x:Name="PART_WindowsFormsHost">
<cbh:myControl5></cbh:myControl5>
</WindowsFormsHost>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
In the class myControl I get the handle to myControl5 so I can use it to adding event handler.
public class myControl : Control
{
public override void OnApplyTemplate ()
{
base.OnApplyTemplate ();
this.windowsFormsHost = GetTemplateChild ("PART_WindowsFormsHost") as WindowsFormsHost;
myControl5 mc5 = this.InnerControl;
mc5.GotFocus += new EventHandler(InnerControl_GotFocus);
.....
}
}
Now my problem:
Each time the Style Layout change, I see that WPF creates a new myControl but never release it. So the memory usage increase each time.
I hope the explaining is so useful, that you can say "Natch, you forgot ..." or something like that.