This is the technical blog of Keyvan Nayyeri, a 29 years old software engineer at Match.Com, speaker and author. You will find content about computer science, programming, and technology on here.
Cool! I'm still here and have enough time to waste with blogging!
In one of my recent posts about a free GridView control for Windows Presentation Foundation I stated that previously I was hosting a traditional Windows Forms GridView in my WPF applications to have a GridView. This is a helpful feature since there are some differences in WPF and Windows Forms controls and the ability to host Windows Forms controls in Windows Presentation Foundation can solve some problems in short time.
Process is simple. First you need to add a HWND to your WPF applications in UI to host Windows Form controls there. Actually you must derive a class from HwndHost base class to be able to do this but thankfully Microsoft has done the main job and has added a default implementation that is suitable for many common needs and it's WindowsFormsHost.
To use this class you need to add two references to System.Windows.Forms and WindowsFormsIntegration assemblies. As you know first one deals with Windows Form controls but second one is an assembly that lets you to add HWND to WPF applications and enables interoperability for WPF with Windows Forms. So you need to add two new namespaces to your WPF application or XAML file to add HWND to them.
Now that you have added these namespaces to application, it's possible to use WindowsFormsHost from Windows Forms Integration to add HWND to your application. This element provides a hosting surface for your Windows Forms controls. you can use its Width and Height properties to set your appropriate size for hosting surface.
WindowsFormsHost can contain controls from Windows Forms as its children. For example I add a DataGridView to my application and set a name for it. Later I'll use this name to refer to this control and get access to its properties and methods.
Now I can go to code behind and write my logic to test this hosted GridView. First I create a new class for Person for my testing purposes.
I create a list of Persons on fly and will use it as data source for my hosted GridView to implement a binding and test my control.
Running this application I get my expected result:
+ Sweet! After a long time today I could sleep like a human!