WPF Image Viewer in VB.NET

The attached project with this article is a simple Image Viewer that allows users to browse an image and display it in WPF and XAML.
  • 7272
This topic briefly discusses the major differences between Windows Presentation Foundation (WPF) versions 3.0 and 3.5. 

Forward and Backward Compatibility

An application built with WPF 3.0 will run on the WPF 3.5 runtime.
An application built with WPF 3.5 will execute on the 3.0 runtime if the application only uses features that are available in WPF 3.0.
WPF 3.5 defines a new XML namespace, http://schemas.microsoft.com/netfx/2007/xaml/presentation. When building an application using WPF 3.5, you can use this namespace or the namespace defined in WPF 3.0.

Targeting a Specific Runtime

Applications built with WPF 3.0 can target any version of the framework greater or equal to the version the application was originally built against. For more information, see How to: Use an Application Configuration File to Target a .NET Framework Version

The following improvements have been made to the application model:

  • Comprehensive add-in support for supporting nonvisual and visual add-ins from standalone applications and XAML browser applications (XBAPs).
  • XBAPs can now run in Firefox.
  • Cookies can be shared between XBAPs and Web applications from the same site of origin.
  • Improved XAML IntelliSense experience for higher productivity.
  • Expanded localization support.

Visual and Nonvisual Add-Ins in WPF

An extensible application exposes functionality in a way that allows other applications to integrate with and extend its functionality. Add-ins are one common way for applications to expose their extensibility. In the .NET Framework, an add-in is typically an assembly that is packaged as a dynamic link library (.dll). The add-in is dynamically loaded by a host application at run time to use and extend services exposed by the host. The host and the add-in interact with each other through a well-known contract, which typically is a common interface that is published by the host application.

Once an application supports add-ins, first-party and third-party developers can create add-ins for it. There are many examples of these types of applications, including Office, Visual Studio, and Microsoft Windows Media Player. For example, the add-in support for Microsoft Windows Media Player allows third parties to create DVD decoders and MP3 encoders.

The .NET Framework implements the building blocks for allowing applications to support add-ins. However, the time and complexity that is required to build that support can be expensive, considering that a robust add-in design needs to handle the following:

  • Discovery: Finding add-ins that adhere to contracts supported by host applications.
  • Activation: Loading, running, and establishing communication with add-ins.
  • Isolation: Using either application domains or processes to establish isolation boundaries that protect applications from potential security and execution problems with add-ins.
  • Communication: Allowing add-ins and host applications to communicate with each other across isolation boundaries by calling methods and passing data.
  • Lifetime Management: Loading and unloading application domains and processes in a clean, predictable manner (see Application Domains Overview).
  • Versioning: Ensuring that host applications and add-ins can still communicate when new versions of either are created.

Rather than requiring you to solve these problems, .NET Framework now includes a set of types, located in the System.AddIn namespace, that are collectively known as the "add-in model". The .NET Framework add-in model provides functionality for each of the common add-in behaviors listed above.

In some scenarios, though, it may also be desirable to allow add-ins to integrate with and extend host application UIs. WPF extends the .NET Framework add-in model to enable this support, which is built around displaying a FrameworkElement owned by an add-in in the UIs of a host application. This enables WPF developers to create applications to support the following common scenarios:

  • Messenger-style application that provide additional services with 3rd party 'buddy" add-ins.
  • Gaming applications designed to host third-party party games.
  • Content Reader applications that host advertisements.
  • Mashup applications that host arbitrary modules; for example, Windows Sidebar.

And, WPF add-ins can be hosted by both standalone applications and XBAPs.

The Image Class

The Image class is used to load and view an image in WPF. This class displays .bmp, .gif, .ico, .jpg, .png, .wdp, and .tiff files. If a file is a multiframe image, only the first frame is displayed. The frame animation is not supported by this class.


Image Class with source property :

<Image Name="ImageViewer1" Source="Creek.jpg" Height="400" Width="400" />

In the above code snippet, UriKind let you set if the image is relative to the application path or has an absolute path.


I create a WPF application with two labels, a button, and an Image control. The XAML code looks like following:


<StackPanel Orientation="Horizontal" Background="LightBlue" Height="40">

    <Label Margin="10,0,0,0" Height="23" Name="Label1">

        Current File:


    <Label Margin="5,0,0,0" Height="25" Name="FileNameLabel" Width="300" />

    <Button Margin="5,0,0,0" Height="23" Name="BrowseButton" Width="75" Click="BrowseButton_Click">




<StackPanel >

    <Image Name="ImageViewer1" Height="400" Width="400" />      



The application UI looks like Figure 1.



Figure 1.


The Browse button click event handler looks like following:


        Private Sub BrowseButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
            Dim dlg As New OpenFileDialog()
            dlg.InitialDirectory = "c:\"
            dlg.Filter = "Image files (*.jpg)|*.jpg|All Files (*.*)|*.*"
            dlg.RestoreDirectory = True

            If dlg.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
                Dim selectedFileName As String = dlg.FileName
                FileNameLabel.Content = selectedFileName
                Dim bitmap As New BitmapImage()
                bitmap.UriSource = New Uri(selectedFileName)
                ImageViewer1.Source = bitmap
            End If
        End Sub

Click on the Browse button let you browse the files and selected file is displayed in the Viewer. See Figure 2.


Figure 2.



This article showed how to use the Image control of WPF to load and view the image files. I will be working with this Image Viewer for a while and will build a full-fledged image viewer.

For more information, see Windows Presentation Foundation Add-Ins Overview.

Firefox Support for XBAPs

A plug-in for WPF 3.5 enables XBAPs to be run from Firefox 2.0, a feature that is not available from WPF 3.0. Key features include the following:
  • If Firefox 2.0 is your default browser, XBAPs honor the configuration. That is, Internet Explorer is not used for XBAPs if Firefox 2.0 is the default.
  • The same security features available to XBAPs running Internet Explorer are available to XBAPs running in Firefox 2.0, including partial-trust security sandboxing. Additional browser-provided security features are browser-specific.


Standalone WPF applications and XBAPs can create, obtain, and delete both session and persistent cookies. In WPF 3.5, persistent cookies can be shared between XBAPs, Web servers, and HTML files that have the same site of origin.

For more information on cookies, see Navigation Overview.

Visual Studio IntelliSense Enhancements

You can now add a new XAML element using the Visual Studio XAML editor, give it a name (using the Name attribute), and refer to it from code-behind and view its members from the IntelliSense explorer.


WPF 3.5 adds support for the following scripts:
  • Bengali
  • Devanagari
  • Gujarati
  • Gurmukhi
  • Kannada
  • Malayalam
  • Oriya
  • Tamil
  • Telugu

For more information, see Globalization for the Windows Presentation Foundation.

Input Method Editor (IME) Support for the TextBox

The FrameworkTextComposition class now has the following properties:

A FrameworkTextComposition is used as the TextCompositionEventArgs..::.TextComposition property when the user enters text into a TextBox by using an IME and the TextInput, TextInputUpdate, or TextInputStart event occurs.

You now have the ability to cache images that are downloaded over HTTP to the local Microsoft Internet Explorer temporary file cache, so that subsequent requests for the image come from local disk, rather than the Internet. Depending on the sizes of your images, this can be a significant network performance improvement. The following members have been added to support this feature:

The BitmapSource..::.DecodeFailed event has been added to notify you when an image fails to load, due to a corrupt header.

The following new features have been added to the 3-D object model.

Input, Focus, and Eventing Support in 3-D

The 3-D object model now supports UIElement concepts such as input, focus, and events. The new classes that provide these services are UIElement3D and its derived classes ContainerUIElement3D and ModelUIElement3D. For examples, see UIElement3D Sphere Sample and Handling Events in 3-D Sample.

Interactive 2-D Content on 3-D

The new class Viewport2DVisual3D provides the support for placing interactive 2-D content onto a 3-D object. For an example, see Interactive 2-D on 3-D Sample.

New Transformation Services

The new classes GeneralTransform3D, GeneralTransform2DTo3D, and GeneralTransform3DTo2D enable transformations between Visual3D objects and from 2-D to 3-D and vice versa.

The following improvements have been made to data binding:

  • A new debugging mechanism makes it easier to debug data bindings.
  • The data model enables validation on the business layer by providing support for the IDataErrorInfo interface. In addition, the validation model now supports using property syntax to set validation rules.
  • The data binding model now supports LINQ and XLINQ.

New Debugging Mechanism

It is now easier to debug data bindings. You can set the new attached property PresentationTraceSources..::.TraceLevel on a binding-related object to receive information about the status of a specific binding. PresentationTraceSources is a static class in the System.Diagnostics namespace.

Support for IDataErrorInfo

The data validation model now supports the IDataErrorInfo interface to enable a business object to determine the validity of the input. The interface defines an indexer that takes a property name and returns a string. The validation rule DataErrorValidationRule, which checks for exceptions returned by the indexer, has been added. For an example, see Business Layer Validation Sample.

Alternative Syntax for Data Validation

The Binding and MultiBinding classes have two new properties, ValidatesOnExceptions and ValidatesOnDataErrors. These two properties provide an alternative to setting ExceptionValidationRule or DataErrorValidationRule in element syntax.

LINQ and XLINQ Support

Improvements have been made to BindingListCollectionView to provide better support for binding to a collection that is of type BindingList<(Of <(T>)>) and for LINQ. The behavior of data bindings with a CollectionView over an IEnumerable has also been improved to provide better performance and better support for binding to results that are produced by LINQ. For a LINQ example, see LINQ Query Sample.

In addition, the data binding model also provides support for XLINQ.


The RichTextBox now preserves custom TextElement objects when it saves the TextElement and when the TextElement participates in clipboard operations. This behavior is supported by the following new APIs:

The RichTextBox has a new property called IsDocumentEnabled. When IsDocumentEnabled is true, UI elements, such as buttons and hyperlinks, accept user input.


TextBoxBase has a new property called UndoLimit, which specifies the maximum number of actions the control references.


SoundPlayerAction can now load audio files that can be identified by both relative and absolute pack uniform resource identifiers (URIs):
  • Resource Files: audio files with a build action of Resource.
  • Content Files: audio files with a build action of Content.
  • Site Of Origin Files: audio files with a build action of None.

Protected Set Accessors

The set accessors of the following properties are now protected rather than internal:

FlowDocumentPageViewer, FlowDocumentScrollViewer, and FlowDocumentReader each have a new public property called Selection. The property gets the TextSelection that represents the selected content in the document.

The annotations framework now exposes the capabilities for matching annotations with the corresponding annotated objects. A new interface, IAnchorInfo, has been added. In addition, a new method, GetAnchorInfo, which returns an IAnchorInfo object, has been added to the AnnotationHelper class.

These new additions enable scenarios in which you need to access the object that the annotation object is anchored to. For an example, see Annotated Document Viewer with Comments Pane Sample.


More Articles

© 2020 DotNetHeaven. All rights reserved.