views:

311

answers:

3

I'm trying to load and host a WPF control in a .net 2.0 windows forms application. The WPF control should only be loaded if .net 3.5 is installed.

I found a link to Hosting WPF Content in an MFC Application and that is about what I'm trying to do but my C++ knowledge isnt sufficient to be able to 'translate' it to .net.

Anyway, here is another link: Hosting WPF Content in a Java Application that doest the same again but I dont know where to start writing that code in .net.

A: 

Hi To host a WPF control in a Win32 form you need to use the ElementHost control. Drop this control on the Window and set it's Child property to the WPF form you want to display.

To find out if .Net 3.5 is installed or not you can try to load an assembly that only exist in 3.5

As an example, here is a method for finding out if Net 3.5 Sp1 is installed or not:


        private static bool IsDotNet35Sp1Installed()
        {
            try
            {
                Assembly.ReflectionOnlyLoad(
                    "System.Data.Entity, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
            }
            catch (FileNotFoundException)
            {
                return false;
            }
            return true;
        }

/Daniel

Daniel Enetoft
This won't work in .Net 2.0. The elementhost object got introduced in .Net 3.0 and the main application has to be build against .Net 2.0
Barfieldmv
Ok, sorry. Did not get that.
Daniel Enetoft
+1  A: 

Your first stop regarding topics like this should be WPF Migration and Interoperability. In particular you'll find there a Walkthrough: Hosting a Windows Presentation Foundation Control in Windows Forms to get you started.

Please note that the Windows Forms host application build in this walkthrough is indeed targeting .NET Framework 2.0 as you desire, despite the fact that ElementHost has been introduced in .NET Framework 3.0.

If you need to shield your application against the absence of these assemblies you'll have to introduce a layer of indirection and only load ElementHost at runtime after successfully detecting .NET Framework 3.5, see below for hints regarding the latter.


.NET Framework version and service pack detection:

Steffen Opel
A: 

I used the following code to load a dll containing a 3.5 wpf control in a .net 2.0 windows form host. The control loaded contains a ElementHost object.

Dim dllPath As String = "C:\ProjectsTest\TestSolution\ActiveXUser\bin\Debug\TestControl.dll"
If Not File.Exists(dllPath) Then
Return
End If

Dim versionInformation As String
versionInformation = Environment.Version.Major.ToString + Environment.Version.Minor

Dim loadedAssembly As [Assembly] = [Assembly].LoadFile(dllPath)

Dim mytypes As Type() = loadedAssembly.GetTypes()

Dim t As Type = mytypes(1)
Dim obj As [Object] = Activator.CreateInstance(t)

versionInformation = Environment.Version.Major.ToString + Environment.Version.Minor
Me.Panel1.Controls.Add(obj)
Barfieldmv