1. Technology

WPF User Controls in VB.NET

They're not the same as reusable Toolbox controls.


Business woman working on computer
AMV Photo/Digital Vision/Getty Images

This article shows you how to code and use WPF "User Controls". Just as there is a Button, Label, and many other components that perform more or less the same function in both Windows Forms and WPF - Windows Presentation Foundation - there is also a new User Control technology just for WPF. In the case of WPF, the name is slightly misleading because it actually functions more as a way of organizing your XAML code than an actual, reusable "ToolBox" control. That's also available but called a "Custom Control". (This article doesn't cover them.) To make matters even worse, there is also an ASP.NET only "User Control" too. That User Control is sometimes called an .ascx file after the file type. (That's not covered here either.)

One of the best ways to keep them straight, since the names don't help much anymore, is to keep in mind that they are all in different namespaces.

  • The original VB.NET UserControl Class in in System.Windows.Forms.
  • The new WPF UserControl Class is in System.Windows.Controls.
  • The ASP.NET UserControl Class is in System.Web.UI.

If you're interested in the Windows Form User control, you might want to try my article, "Windows Forms User Controls".

What are WPF User Controls for?

If you have been programming WPF applications using XAML, you know now that they can get pretty confusing and long. Here's just the XAML code that you might use for just a ToolTip. The actual text is buried 7 levels deep in XAML code and there are 18 lines of code ... just to display a ToolTip!

<Window x:Class="Window1"
   Title="Window1" Height="300" Width="300">
                     The tooltip

This example was constructed to make a point, but XAML files do go on for pages and pages. At the same time, since XAML is "descriptive" (the code shows "what" is being done, it doesn't describe "how"), once someone has worked out the exact code to make something look just right, there is absolutely no sense in repeating that code. This is where WPF User Controls come in! To illustrate how to do this, let's make a control out of something that was programmed in a different About Visual Basic article.

In the tutorial for WPF at About Visual Basic, a font viewer was programmed to demonstrate Data Binding in WPF. Here's what the finished product looks like while running:

Click Here to display the illustration
Click the Back button on your browser to return

If you would like to review that part of the tutorial, you can find it at This Link.

On the next page, we construct the code necessary to turn the font viewer into a WPF User Control.

  1. About.com
  2. Technology
  3. Visual Basic
  4. Learn VB.NET
  5. WPF User Control VB.NET

©2014 About.com. All rights reserved.