Loading .net 3.5 wpf-forms in a .net 2.0 application

对着背影说爱祢 提交于 2019-12-02 11:07:11

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

Steffen Opel

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:

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!