Skip to content

Creating a Printer selection ComboBox with default printer

by Samuel Moura on August 13th, 2010

In this quick tutorial I will show you how to create a ComboBox that lists all the printers installed on your computer and automatically selects the default printer.

image

In my case I had to setup such ComboBox so that a tool which users can occasionally execute, can be configured on the application I am currently working on.

In this tutorial I am assuming you are knowledge about .NET, c#, WPF and the MVVM pattern.

1. Retrieving the list of installed printers in .NET

Getting a list of installed printers is quite easy in .NET. You just have to use the PrinterSettings class on your ViewModel as follows:

public PrinterSettings.StringCollection InstalledPrinters
{
   get
   {
      return PrinterSettings.InstalledPrinters;
   }
}

Now you can directly bind the ItemsSource of your ComboBox to this collection:

<ComboBox ItemsSource="{Binding InstalledPrinters}"/>

Since this is a StringCollection exposed by a static class you can use static markup to directly bind your ComboBox to the PrinterSettings class:

<ComboBox ItemsSource="{x:Static Printing:PrinterSettings.InstalledPrinters}"/>

2. Setting the default printer selected

The first time you show your installed printers ComboBox you will probably wish to select the DefaultPrinter as your default. For this you have to actually instantiate the PrinterSettings class:

public string SelectedPrinter { get; set; }

MyViewModel()
{
   var printerSettings = new PrinterSettings();
   SelectedPrinter = printerSettings.PrinterName;
}

And that’s it, you now have a ComboBox with the list of printers. I hope this helps!

Conclusion

It should be pretty straight forward to create a special kind of control (PrinterComboBox) that encapsulates all this stuff and can be reused within your XAML.

From → WPF

2 Comments
  1. This is quite helpful. Would like if you could write a tutorial on printing using the default printer.

Trackbacks & Pingbacks

  1. DotNetShoutout

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS

*