Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Mixing WinForm ListView with WPF

0.00/5 (No votes)
8 Dec 2017 1  
Grouping and sorting in a WinForm listview fails in a WPF application unless Visual Styles are enabled.

Introduction

In a current project, I was tasked to add a WinForms project from an old application into a new WPF application I was building. No real problem, right? Wrong!

In the legacy project's window was a listview, set up with column sorting and automatic grouping when the user clicks on the column header. In the old project, sorting and grouping worked beautifully! Attached to the new application, neither sorting nor grouping worked.

What went wrong??

Background

The legacy application generated several reports, most of which were no longer considered useful. The decision was made to create a new application which, among other things would generate new, useful reports. Once completed, the legacy application would be discarded.

You can guess what happened — people complained that some of the old reports WERE useful! Fortunately, they were all located in one Visual Studio project. I added that project to the new WPF application and added the necessary linkages. Voilà! I could access the reports.

The fly in the ointment – grouping and sorting did not work.

I did an Internet search and found several articles which told me what to do, but they were written for C# programmers. In C#, the "Main" is accessible and can be easily modified by the programmer. Just add:

Application.EnableVisualStyles();

to the Main routine. Alas! My employer says we use Visual Basic. The Microsoft article said to add:

<System.STAThread()> _
Public Shared Sub Main()

but this only resulted in an error message complaining about two Main routines.

Solution

The Microsoft article also said that visual styles must be enabled before any windows of the application are opened. This led me to think about the application initialization sequence in Visual Basic. The "New" subroutine uses the "InitializeComponent()" to instantiate the components of the window, including the window itself! Therefore, I added the following New subroutine to MainWindow.xaml.vb:

Public Sub New()

     ' This line runs before Windows objects are instantiated.
     System.Windows.Forms.Application.EnableVisualStyles()

     ' This call is required by the designer.
     InitializeComponent()

     ' Add any initialization after the InitializeComponent() call.

End Sub  ' New

Sorting and grouping now work as expected!

History

Date Change
2017-12-07 Original version

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here