Logo
HOWTO: Initialize the usercontrol of a toolwindow from a Visual Studio package.

Author: Carlos J. Quintero (Microsoft MVP) Applies to: Microsoft Visual Studio 2010
Date: July 2014   Microsoft Visual Studio 2012
      Microsoft Visual Studio 2013
Introduction

When you create a toolwindow with the Visual Studio package wizard, a WPF usercontrol is hosted inside the toolwindow. This article explains how to initialize that usercontrol passing it the package.

More Information

After the Visual Studio package wizard has created the usercontrol, add it a method named for example "Initialize" that receives as parameter an instance of your package:

Language: C#   Copy Code Copy Code (IE only)
public partial class MyControl : UserControl
{
   public MyControl()
   {
      InitializeComponent();
   }

   public void Initialize(MyVSPackageCSharpPackage package)
   {
      System.Windows.Forms.MessageBox.Show(package.ToString());
   }
}
Language: VB.NET   Copy Code Copy Code (IE only)
Public Class MyControl

   Public Sub Initialize(myPackage As MyVSPackageVBPackage)

      System.Windows.Forms.MessageBox.Show(myPackage.ToString())

   End Sub

End Class

In the MyToolWindow.cs or MyToolWindow.vb file, override the OnToolWindowCreated method to get the instance of the package and pass it to the Initialize method of the usercontrol. Note: if you try to get the package instance in the constructor of the MyToolWindow class, it can be null, so overriding the OnToolWindowCreated method is required.

Language: C#   Copy Code Copy Code (IE only)
public class MyToolWindow : ToolWindowPane
{
   MyControl m_myControl;

   public MyToolWindow(): base(null)
   {
      this.Caption = Resources.ToolWindowTitle;
      this.BitmapResourceID = 301;
      this.BitmapIndex = 1;

      m_myControl = new MyControl();

      base.Content = m_myControl;
   }  

   public override void OnToolWindowCreated()
   {
      MyVSPackageCSharpPackage myPackage;
 
      base.OnToolWindowCreated();

      myPackage = (MyVSPackageCSharpPackage)base.Package;

      m_myControl.Initialize(myPackage);
   }
}
Language: VB.NET   Copy Code Copy Code (IE only)
Public Class MyToolWindow
   Inherits ToolWindowPane

   Private m_myControl As MyControl

   Public Sub New()

      MyBase.New(Nothing)
      Me.Caption = Resources.ToolWindowTitle
      Me.BitmapResourceID = 301
      Me.BitmapIndex = 1

      m_myControl = New MyControl()

      Me.Content = m_myControl

   End Sub

   Public Overrides Sub OnToolWindowCreated()

      Dim myPackage As MyVSPackageVBPackage
      MyBase.OnToolWindowCreated()

      myPackage = DirectCast(MyBase.Package, MyVSPackageVBPackage)

      m_myControl.Initialize(myPackage)

   End Sub

End Class


Go to the 'Visual Studio Extensibility (VSX)' web site for more articles like this (Articles section)