Sunday, October 18, 2009

Windows Forms & WPF Element Host Bug And How to Fix It

If you haven't had the chance to look at what Microsoft did with the advent of the Windows Presentation Framework (WPF), I suggest you check it out.  As a revamp of how Windows Applications are written it is pretty spot on with what needed to be done.  I could ramble about how much I like WPF for a while but that's not the point of this post. 

In an ideal world we would be able to rewrite our applications with new technologies, especially ones that improve our maintainability and improve its over all quality.  However, in the real world this is not really feasible.  We have budget, time, and customer constraints.  Many times existing code has domain knowledge impeded in a non-extractable way.    As much we as developers want to play with technologies and use the latest greatest things these constraints don't allow us to.  Microsoft has recognized that we want to use new technologies in existing applications or we want to take an incremental approach to transition our applications.  In order to help with either of these plans they have provided the ElementHost control which allows you to put WPF controls on a Windows Form. 

The ElementHost is great conceptually and great when it is working, however it has a fundamental bug.  What is this bug you may ask?  The bug is that by default the controls contained in the element host will always be disabled because the enable property won't propagate through to them.  This basically makes them read only controls.  The good news is that there is a work around for it, however it is non-intuitive because it uses Win32 Interop.  I was only able to know what to do once I found Microsoft's page about the bug.  There are not really any references to it unless you search very specifically.  The solution to the problem can be found here: http://support.microsoft.com/kb/955753 

I recommend you create a class that derive a class from ElementHost and having that as part of your repository and use that for incorperating WPF controls into windows forms.

A couple side notes.  This is only necessary if you have a Windows Form that you want to place WPF controls on.  You can open a WPF Window in a Windows Form application as if was just another form so this is not necessary if you just want to combine WPF and Windows Forms inside the same application. 

1 comment:

  1. This comment has been removed by a blog administrator.

    ReplyDelete