Search code examples
c#wpfdatatemplate

How to set WinFormHost object dynamically?


I am wrapping Windows Form legacy control inside WPF control , I am doing this for a few Windows Form controls. ie:

 // WinFormHost control, only AWrapper is shown here, but there 
 //are BWrapper, CWrapper etc
 public class AWrapper : WindowsFormsHost 
 {
   Child=new ALegacyWinFormControl();
 }

//WPF control, similarly there are BControl, CControl etc
<UserControl x:Class="AControl">
    <local:AWrapper  />
</UserControl>

At my ResourceDictionary I am defining a key for each WPF controls

// each WPF control has a key
<ResourceDictionary>
    <DataTemplate x:Key="AControlKey">
        <AControl />
    </DataTemplate>
    <DataTemplate x:Key="BControlKey">
        <BControl />
    </DataTemplate>
</ResourceDictionary>

There is one layer of duplication that I want to eliminate-- I will have to define each WPF control for each WindowsFormsHost wrapper, which is redundant. Is there anyway that I can do away with the UserControl object, and connect the DataTemplate straight with the WindowsFormsHost control? ie: I am looking at something like this:

// This wouldn't work
<ResourceDictionary>
    <DataTemplate x:Key="AControlKey">
        <AWrapper/>
    </DataTemplate>
    <DataTemplate x:Key="BControlKey">
        <BWrapper/>
    </DataTemplate>
</ResourceDictionary>

But the above doesn't seem to work. Anyway to make the above work? Is it possible at all?

Edit:


Solution

  • This should work provided that AWrapper is a WindowsFormsHost:

    <DataTemplate x:Key="AControlKey">
        <local:AWrapper/>
    </DataTemplate>
    

    Sample usage:

    <ContentControl Content="." ContentTemplate="{StaticResource AControlKey}" />
    

    No UserControl is involved.

    local maps to the namespace in which the AWrapper class is defined:

    xmlns:local="clr-namespace:WpfApplication1"