π Lecture 23 β Touch Events and Manipulation Events
π Overview: This lecture introduces touch event handling in WPF, covering basic touch events (TouchDown, TouchMove, TouchUp) and advanced manipulation events that combine multi-touch input for gestures like translation, rotation, and scaling. It also covers inertia simulation and boundary feedback to create natural, fluid touch interactions.
ποΈ Topics Covered
The lecture explains touch events with a fingerprint tracking example, then moves to manipulation events (manipulationstarting, manipulationdelta, manipulationcompleted) with examples for moving, rotating, and zooming photos. It covers inertia handling for smooth deceleration, boundary feedback via reportboundaryfeedback, and a spin prize wheel example using rotation-only manipulation. Finally, it mentions ScrollViewer panning support and the Surface Toolkit for Windows Touch.
π Lecture Summary
Touch Events Example
The lecture begins with an example using touch events to track multiple finger touches on a Canvas. A Dictionary<touchdevice, Image> named fingerprints keeps track of which images are associated with which touch devices.
π Definition β TouchDevice: Represents an individual finger or stylus input. Each touch contact gets a unique TouchDevice instance.
π Example: When a user touches the Canvas, the OnTouchDown handler captures the touch device, creates a new Image (fingerprint.png), positions it at the touch point using a TranslateTransform, adds the image to the dictionary and the Canvas children. On OnTouchMove, the image follows the finger by updating the Transform's X and Y coordinates. On OnTouchUp, the touch capture is released, and the image is removed from both the Canvas and the dictionary.
Manipulation Events Overview
Manipulation events (manipulationstarting, manipulationstarted, manipulationdelta, manipulationcompleted) combine information from multiple touch events to enable gestures. They work when IsManipulationEnabled=true is set on the element or a parent, and basic touch events are not handled.
π‘ Why this matters: Manipulation events automatically interpret multi-touch input (e.g., two-finger pinch to zoom, rotate gestures) without requiring you to write complex gesture recognition logic.
π Definition β ManipulationDelta: Contains Translation, Scale, Rotation, and Expansion (similar to Scale but in pixels instead of scale factor). ManipulationDeltaEventArgs provides both DeltaManipulation (change since last event) and CumulativeManipulation (total change since manipulation started).
Manipulation Events Example: Move, Rotate, Zoom
The example shows how to move, rotate, and zoom a photo using manipulation events. The XAML sets IsManipulationEnabled="True" on the Canvas and uses a MatrixTransform on the Image.
π Formula: Matrix transforms: Matrix.Translate(dx, dy) β moves the image; Matrix.RotateAt(angle, originX, originY) β rotates around a point; Matrix.ScaleAt(sx, sy, originX, originY) β scales relative to a point.
π Example: In the Canvas_ManipulationDelta event handler, the code gets the existing Matrix from the Image's RenderTransform, applies e.DeltaManipulation.Translation.X/Y, e.DeltaManipulation.Rotation (using RotateAt with e.ManipulationOrigin), and e.DeltaManipulation.Scale.X/Y (using ScaleAt with e.ManipulationOrigin), then sets transform.Matrix = matrix and marks the event as handled.
Manipulation Container
Manipulations are always performed relative to a manipulation container. By default, it's the element with IsManipulationEnabled=true, but you can customize it by handling ManipulationStarting and setting e.ManipulationContainer.
Inertia
Inertia allows natural deceleration after touch gestures. The ManipulationInertiaStarting event fires when all fingers lose contact, before the completed event. You can set properties on TranslationBehavior, RotationBehavior, and/or ExpansionBehavior to control inertia.
π Definition β TranslationBehavior has: DesiredDisplacement, DesiredDeceleration, and InitialVelocity. RotationBehavior has: DesiredRotation, DesiredDeceleration, and InitialVelocity. ExpansionBehavior has: DesiredExpansion, DesiredDeceleration, InitialRadius, and InitialVelocity.
π Example: To enable inertia, handle Canvas_ManipulationInertiaStarting and set e.TranslationBehavior.DesiredDeceleration = 0.01; e.RotationBehavior.DesiredDeceleration = 0.01; e.ExpansionBehavior.DesiredDeceleration = 0.01;. This causes the manipulation to continue with decreasing speed after fingers are lifted, producing smooth delta events until it stops.
Boundary Feedback
The ManipulationBoundaryFeedback event handles boundary awareness. Inside a ManipulationDelta event handler, you can call e.ReportBoundaryFeedback() to make the window bounce similar to iPhone bounce-list behavior.
Spin Prize Wheel Example
The lecture demonstrates a spin prize wheel with rotation-only manipulation. The XAML uses a Grid with IsManipulationEnabled="True", an Image with RenderTransformOrigin="0.5,0.5" (center of image) and a RotateTransform, plus an arrow image.
π Example: In Grid_ManipulationStarting, set e.Mode = ManipulationModes.Rotate to restrict input to rotation only. In Grid_ManipulationDelta, add e.DeltaManipulation.Rotation to the RotateTransform's Angle. In Grid_ManipulationInertiaStarting, set e.RotationBehavior.DesiredDeceleration = 0.001 for slow deceleration. In Grid_ManipulationCompleted, you can show what the user won.
Scrolling and Surface Toolkit
You can enable panning in a ScrollViewer by setting its PanningMode property to HorizontalOnly, VerticalOnly, HorizontalFirst, VerticalFirst, or Both. The Surface Toolkit for Windows Touch provides WPF controls optimized for multi-touch, including "Surface versions" of common controls (e.g., SurfaceButton, SurfaceCheckBox) and brand-new controls (e.g., ScatterView, LibraryStack).
β Key Takeaways
Manipulation events (starting, delta, inertia starting, completed) must have IsManipulationEnabled=true to work. The ManipulationDelta event provides Translation, Rotation, and Scale deltas that can be applied to a MatrixTransform for smooth gesture handling. Inertia is enabled by setting deceleration values in ManipulationInertiaStarting, producing natural deceleration after touch release. The ManipulationMode property can restrict gestures to specific types (e.g., Rotate only). For boundary feedback, call ReportBoundaryFeedback() in the delta handler to create bounce effects.
π§ Quick Revision Questions
- What dictionary is used to track which images belong to which touch devices in the touch events example?
- What property must be set to true on a Canvas (or parent element) to enable manipulation events?
- In the ManipulationDelta event handler, which three matrix operations are applied to the photo's MatrixTransform?
- What event fires when all fingers lose contact from the screen, enabling inertia configuration?
- How do you restrict manipulation to only rotation gestures in the ManipulationStarting event?
π Lecture 24 β Commands and Input Events in WPF
π Overview: This lecture introduces WPF commands as an abstract, loosely coupled alternative to direct event handling, enabling features like automatic input gestures, enable/disable logic, and two-way communication between controls. Understanding commands is essential for building maintainable WPF applications with standardized user interactions.
ποΈ Topics Covered
Commands as abstract event wrappers (e.g., Cut, Copy, Paste), the ICommand interface (Execute, CanExecute, CanExecuteChanged), WPF built-in command libraries (ApplicationCommands, ComponentCommands, MediaCommands, NavigationCommands, EditingCommands), command binding with CommandBindings and event handlers, routing commands via bubbling, XAML vs code-behind implementation, KeyBindings and MouseBindings, CommandTarget property, and controls with built-in command bindings (e.g., TextBox).
π Lecture Summary
Commands Overview
Commands are a more abstract and loosely coupled version of events, used for operations like Cut, Copy, and Paste. They are exposed in various ways and can be enabled or disabledβfor example, disabling Paste when thereβs nothing to paste. Two-way communication becomes cumbersome if you hard-code control lists, but WPF commands solve this. WPF defines a number of built-in commands with automatic support for input gestures (such as keyboard shortcuts). Some WPF controls have built-in behavior tied to various commands.
π Definition β ICommand: Any object implementing ICommand can work as a Command. It defines three members: Execute, CanExecute, and CanExecuteChanged.
For Cut, Copy, and Paste, you could define three classes implementing ICommand, store them (e.g., as static fields of the main Window), call Execute from relevant event handlers (when CanExecute returns true), and handle the CanExecuteChanged event to toggle the IsEnabled property on UI elements. Controls have logic to interface with commands through the Command property.
π Example: You can set a button's command in XAML like this:
<Button Command="Help" Content="{Binding RelativeSource={RelativeSource Self}, Path=Command.Text}"/>
This binds the button to the built-in ApplicationCommands.Help command.
Predefined Built-in Commands
WPF provides several categories of built-in commands:
- ApplicationCommands: Close, Copy, Cut, Delete, Find, Help, New, Open, Paste, Print, PrintPreview, Properties, Redo, Replace, Save, SaveAs, SelectAll, Stop, Undo, and more.
- ComponentCommands: MoveDown, MoveLeft, MoveRight, MoveUp, ScrollByLine, ScrollPageDown, ScrollPageLeft, ScrollPageRight, ScrollPageUp, SelectToEnd, SelectToHome, SelectPageDown, SelectPageUp, and more.
- MediaCommands: ChannelDown, ChannelUp, DecreaseVolume, FastForward, IncreaseVolume, MuteVolume, NextTrack, Pause, Play, PreviousTrack, Record, Rewind, Select, Stop, and more.
- NavigationCommands: BrowseBack, BrowseForward, BrowseHome, BrowseStop, Favorites, FirstPage, GoToPage, LastPage, NextPage, PreviousPage, Refresh, Search, Zoom, and more.
- EditingCommands: AlignCenter, AlignJustify, AlignLeft, AlignRight, CorrectSpellingError, DecreaseFontSize, DecreaseIndentation, EnterLineBreak, EnterParagraphBreak, IgnoreSpellingError, IncreaseFontSize, IncreaseIndentation, MoveDownByLine, MoveDownByPage, MoveDownByParagraph, MoveLeftByCharacter, MoveLeftByWord, MoveRightByCharacter, MoveRightByWord, and more.
All instances of RoutedUICommand implement ICommand and support bubbling (events travel up the element tree).
Command Binding
If you set HelpButton.Command = ApplicationCommands.Help; without a command binding, the button will always be disabled. We need to add a CommandBinding to the element or a parent element (due to bubbling).
π Definition β CommandBinding: All UIElement objects have a CommandBindings collection. You add a command binding to link a command to its Execute and CanExecute handlers.
π Formula:
this.CommandBindings.Add(new CommandBinding(ApplicationCommands.Help, HelpExecuted, HelpCanExecute));
The CanExecute handler determines if the command can run:
void HelpCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
The Execute handler defines what happens:
void HelpExecuted(object sender, ExecutedRoutedEventArgs e)
{
System.Diagnostics.Process.Start("http://www.adamnathan.net/wpf");
}
π‘ Why this matters: Without adding a command binding, even though the command is set, the button remains disabled because there's no handler to tell WPF that the command can execute.
XAML Command Binding
Commands can be entirely defined in XAML using a type converter. The CommandConverter type converter allows using the command name directly as a string.
π Example β Complete XAML implementation of an About dialog with Help command:
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="AboutDialog"
Title="About WPF Unleashed" SizeToContent="WidthAndHeight"
Background="OrangeRed">
<Window.CommandBindings>
<CommandBinding Command="Help"
CanExecute="HelpCanExecute" Executed="HelpExecuted"/>
</Window.CommandBindings>
<StackPanel>
<Label FontWeight="Bold" FontSize="20" Foreground="White">
WPF 4 Unleashed
</Label>
<Label>Β© 2010 SAMS Publishing</Label>
<Label>Installed Chapters:</Label>
<ListBox>
<ListBoxItem>Chapter 1</ListBoxItem>
<ListBoxItem>Chapter 2</ListBoxItem>
</ListBox>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
<Button MinWidth="75" Margin="10" Command="Help"
Content="{Binding RelativeSource={RelativeSource Self}, Path=Command.Text}"/>
<Button MinWidth="75" Margin="10">OK</Button>
</StackPanel>
<StatusBar>You have successfully registered this product.</StatusBar>
</StackPanel>
</Window>
The corresponding C# code-behind:
using System.Windows;
using System.Windows.Input;
public partial class AboutDialog : Window
{
public AboutDialog()
{
InitializeComponent();
}
void HelpCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
void HelpExecuted(object sender, ExecutedRoutedEventArgs e)
{
System.Diagnostics.Process.Start("http://www.adamnathan.net/wpf");
}
}
Input Gestures β KeyBindings and MouseBindings
Commands automatically handle input gestures. For example, ApplicationCommands.Help already maps to F1. You can also add custom KeyBindings and MouseBindings manually.
this.InputBindings.Add(
new KeyBinding(ApplicationCommands.Help, new KeyGesture(Key.F2)));
In XAML:
<Window.InputBindings>
<KeyBinding Command="Help" Key="F2"/>
<KeyBinding Command="NotACommand" Key="F1"/>
</Window.InputBindings>
Controls with Built-in Command Bindings
Some controls have built-in command bindings. For example, TextBox automatically responds to Ctrl+Z (Undo), Ctrl+C (Copy), etc. This enables rich interaction between controls without direct coupling.
π Example β Commands with CommandTarget property:
<StackPanel Orientation="Horizontal" Height="25">
<Button Command="Cut" CommandTarget="{Binding ElementName=TextBox}"
Content="{Binding RelativeSource={RelativeSource Self}, Path=Command.Text}"/>
<Button Command="Copy" CommandTarget="{Binding ElementName=TextBox}"
Content="{Binding RelativeSource={RelativeSource Self}, Path=Command.Text}"/>
<Button Command="Paste" CommandTarget="{Binding ElementName=TextBox}"
Content="{Binding RelativeSource={RelativeSource Self}, Path=Command.Text}"/>
<Button Command="Undo" CommandTarget="{Binding ElementName=TextBox}"
Content="{Binding RelativeSource={RelativeSource Self}, Path=Command.Text}"/>
<Button Command="Redo" CommandTarget="{Binding ElementName=TextBox}"
Content="{Binding RelativeSource={RelativeSource Self}, Path=Command.Text}"/>
<TextBox x:Name="TextBox" Width="200"/>
</StackPanel>
The Button and TextBox have no direct knowledge of each other, yet through commands we achieve rich interaction. The more standardization on built-in commands, the more seamless and declarative the interaction between controls.
π‘ Why this matters: Using CommandTarget lets you specify which control the command acts upon, enabling multiple controls to share the same command without hard-coded references.
β Key Takeaways
Commands provide an abstract, loosely coupled alternative to direct event handling, with built-in support for input gestures, enable/disable logic, and bubbling behavior. WPF includes five categories of built-in commands: ApplicationCommands, ComponentCommands, MediaCommands, NavigationCommands, and EditingCommands, all implemented as RoutedUICommand types. Every command must be connected to a CommandBinding that provides CanExecute and Execute handlers; without this, the command UI remains disabled. The CommandTarget property allows commands to target a specific control (like a TextBox) without coupling the controls together. Standardizing on built-in commands enables seamless, declarative interactions between controls, reducing hard-coded logic and improving maintainability.
π§ Quick Revision Questions
- What three members must the ICommand interface define?
- Name at least four categories of built-in commands in WPF and give one example from each.
- Why does a button with
Command="Help"remain disabled until you add a CommandBinding? - What is the purpose of the
CommandTargetproperty when used with commands? - How does command bubbling work in relation to the element tree?
π Lecture 25 β Structuring and Deploying an Application
π Overview: This lecture focuses on structuring WPF applications, including window management, dialogs, and application lifecycle. It covers how to create single-instance apps, persist data using isolated storage, and deploy applications using ClickOnce vs Windows Installer, essential for building robust desktop applications.
ποΈ Topics Covered
The lecture covers WPF window types and properties, parent-child window relationships, modal and modeless dialogs, the Application class and its lifecycle events, single-instance application creation using mutex, splash screens, common dialogs like PrintDialog, isolated storage for data persistence, and deployment options including ClickOnce and Windows Installer.
π Lecture Summary
Structuring and Deploying an Application
The lecture begins by discussing how to structure and deploy WPF applications, covering standard Windows apps, partial trust web apps, and loose XAML. The Photo Gallery example is used throughout. A WPF Window is a Win32 window with the same chrome (non-client area), taskbar behavior, and properties like Icon, Title, WindowStyle, Topmost, and ShowInTaskbar. You can set position using Left and Top properties or WindowStartupLocation to CenterScreen or CenterOwner.
π Definition β Window: A WPF window that inherits from Win32 window, with standard chrome and taskbar behavior.
π Example: Setting window startup location: WindowStartupLocation=CenterScreen
Child Windows
Any number of child windows can be created by instantiating a Window derived class and calling Show. A child window behaves like a parent window but closes when the parent closes and is also minimized, also called a modeless dialog. Another approach is setting the Owner property after the parent is shown, using the OwnedWindows property. Windows have Activated & Deactivated events. Use the Activate method like SetForegroundWindow. Set ShowActivated=false to not show initially.
π Formula: Child window creation β ChildWindow child = new ChildWindow(); child.Show();
π‘ Why this matters: Proper window management prevents orphaned windows and ensures clean UI lifecycle.
Override Methods for Window Lifecycle
The code shows overriding OnClosing, OnClosed, and OnInitialized methods in the MainWindow class:
- OnClosing: Uses
CancelEventArgsto allow cancellation (e.g., prompt user) - OnClosed: Perform cleanup (e.g., persist favorites)
- OnInitialized: Restore state (e.g., retrieve persisted favorites)
protected override void OnClosing(CancelEventArgs e)
{
base.OnClosing(e);
if (MessageBox.Show("Are you sure you want to close Photo Gallery?",
"Annoying Prompt", MessageBoxButton.YesNo, MessageBoxImage.Question)
== MessageBoxResult.No)
e.Cancel = true;
}
π Definition β DispatcherObject: Cannot be accessed from a different thread, which avoids many threading issues.
Application Class and Main()
The Application class manages the application lifecycle. You can create a message loop to process Windows messages. The Main() method must have [STAThread] attribute. Two approaches:
- Create Application explicitly:
[STAThread]
public static void Main()
{
Application app = new Application();
MainWindow window = new MainWindow();
window.Show();
app.Run(window);
}
- Use StartupUri in XAML:
[STAThread]
public static void Main()
{
Application app = new Application();
app.StartupUri = new Uri("MainWindow.xaml", UriKind.Relative);
app.Run();
}
The App.xaml file is assigned ApplicationDefinition build action, which generates App.g.cs. This file contains the auto-generated Main() method.
π Definition β Application Class: Manages application lifetime, window collection, and provides events like Startup, Exit, Activated, Deactivated, SessionEnding.
Single Instance Application
To create a single-instance application, use a Mutex. The Mutex constructor's first parameter indicates ownership, and the out parameter indicates if this is the first instance.
bool mutexIsNew;
using (System.Threading.Mutex m =
new System.Threading.Mutex(true, uniqueName, out mutexIsNew))
{
if (mutexIsNew)
// This is the first instance. Run the application.
else
// There is already an instance running. Exit!
}
π Definition β Mutex: A synchronization primitive used to ensure only one instance of an application runs at a time.
Splash Screen
A splash screen can be created in a WPF project by adding a new item β Splash Screen. The image gets build action SplashScreen. Note: Nothing fancy because WPF isn't loaded yet.
Modal Dialogs and Common Dialogs
Modal dialogs include common dialogs provided by Win32. Instantiate, call ShowDialog(), and process the result.
void printMenu_Click(object sender, RoutedEventArgs e)
{
PrintDialog pd = new PrintDialog();
if (pd.ShowDialog() == true) // Result could be true, false, or null
pd.PrintVisual(image, ...);
}
A window shown as a dialog sets its DialogResult to bool. Setting it closes the window, or set Button's IsDefault property to true.
void okButton_Click(object sender, RoutedEventArgs e)
{
this.DialogResult = true;
}
π Definition β ShowDialog(): Displays a window as a modal dialog, returning a nullable bool (true, false, or null).
Persisting and Restoring Data
Use .NET Isolated Storage for persisting data. Physically located in the user's Documents folder in a hidden folder. The VS-generated Settings class provides an easier but strongly-typed alternative in app.config.
OnClosed (write data):
IsolatedStorageFile f = IsolatedStorageFile.GetUserStoreForAssembly();
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream("myfile", FileMode.Create, f))
using (StreamWriter writer = new StreamWriter(stream))
{
foreach (TreeViewItem item in favoritesItem.Items)
writer.WriteLine(item.Tag as string);
}
OnInitialized (read data):
IsolatedStorageFile f = IsolatedStorageFile.GetUserStoreForAssembly();
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream("myfile", FileMode.OpenOrCreate, f))
using (StreamReader reader = new StreamReader(stream))
{
string line = reader.ReadLine();
while (line != null)
{
AddFavorite(line);
line = reader.ReadLine();
}
}
π Definition β Isolated Storage: A .NET mechanism for storing data in a user-specific, application-specific location, physically in the user's Documents folder.
ClickOnce vs Windows Installer
Windows Installer benefits: custom setup UI (EULA), control over file installation location, arbitrary code at setup time, install shared assemblies in GAC, register COM components and file associations, install for all users, offline installation from CD.
ClickOnce benefits: built-in support for automatic updates and rollback, web-like "go-away" experience or start menu entry, all files in isolated area (no effect on other apps), clean uninstallation, partial trust support via .NET Code Access Security.
π Definition β ClickOnce: A deployment technology that provides automatic updates, isolated installation, and partial trust execution.
β Key Takeaways
- WPF Windows are Win32 windows with standard chrome and behavior; child windows can be modeless or modal via Show/ShowDialog, and must use Owner for owned windows.
- The Application class manages lifecycle events (Startup, Exit, Activated, SessionEnding) and provides a Window collection and ShutdownMode; Main() must be [STAThread] and use App.Run().
- Single-instance applications use a Mutex to detect and prevent multiple instances; the Mutex constructor's out parameter indicates if it's the first instance.
- Data persistence uses IsolatedStorageFile with StreamWriter/StreamReader in OnClosed/OnInitialized overrides, or the VS-generated Settings class in app.config.
- Deployment choices: ClickOnce offers automatic updates and partial trust, while Windows Installer provides full control, custom setup, GAC installation, and all-users installation.
π§ Quick Revision Questions
- What are the two ways to create child windows in WPF, and what is the difference between them?
- How does the Application class manage the application lifecycle, and what events does it provide?
- Explain how to implement a single-instance application using Mutex in WPF.
- Describe the steps to persist and restore data using Isolated Storage in the OnClosed and OnInitialized methods.
- Compare ClickOnce and Windows Installer deployment: list three advantages of each approach.
π Lecture 26 β Navigation-Based Applications
π Overview: This lecture covers navigation-based applications in WPF, exploring how to organize user interfaces around navigation using Pages, NavigationWindow, and Frame containers. It explains the journal system, navigation methods, data passing techniques between pages, and the PageFunction pattern for returning data.
ποΈ Topics Covered
Navigation containers (NavigationWindow and Frame), Page element fundamentals, Navigation methods (Navigate, Hyperlinks, Journal), Journal system and custom content states, Navigation events, Data passing between pages, and PageFunction for returning data. The lecture uses a photo gallery application as a running example to demonstrate navigation concepts.
π Lecture Summary
Navigation-Based Applications
Navigation-based apps include Windows Explorer, Media Player, and Photo Gallery. Navigation support can be used for wizards or to organize the entire UI around navigation. Content is typically placed in a Page, which is a simpler version of Window, then hosted in a NavigationWindow or a Frame. These containers provide support for navigating, a history journal, and navigation-related events.
π‘ Why this matters: Navigation containers allow building multi-page applications with standard forward/back navigation, similar to web browsers.
π Definition β NavigationWindow: A top-level window with built-in navigation UI (back/forward buttons on top).
π Definition β Frame: A navigation container that works like an HTML frame or iframe, without default navigation UI (though it can be shown).
<navigationwindow
Xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
Xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="photogallery.Container"
Title="Photo Gallery" Source="mainpage.xaml"
/>
Page Element
The Page element does everything Window does except for OnClosed and OnClosing events. A navigation-enabled version points the startup URI to the NavigationWindow and references MainPage.xaml as content.
<Page x:Class="photogallery.mainpage"
Title="Photo Gallery" Loaded="Page_Loaded">
<!-- Application-specific content -->
</Page>
Page can interact with its navigation container using the NavigationService class, which exposes functionality regardless of whether the container is a NavigationWindow or Frame. You can get an instance by calling NavigationService.GetNavigationService(page) or use the page's NavigationService property.
Example: Setting a title for the drop-down menu on Back/Forward buttons:
this.NavigationService.Title = "Main Photo Gallery Page";
Example: Refreshing the current Page:
this.NavigationService.Refresh();
Page also has properties like WindowHeight, WindowWidth, and WindowTitle that control parent container behavior, settable both in code and XAML.
Navigation Methods
Navigation can be performed in three main ways:
- Calling the Navigate method
- Using Hyperlinks
- Using the Journal
Navigate method can navigate to a page instance or via URI:
// Navigate to a page instance
PhotoPage nextPage = new PhotoPage();
this.NavigationService.Navigate(nextPage);
// Or navigate to a page via a URI
this.NavigationService.Navigate(new Uri("photopage.xaml", UriKind.Relative));
The root of XAML must be "Page". Navigation can also go to HTML:
this.NavigationService.Navigate(new Uri("http://www.adamnathan.net/wpf"));
Two additional properties useful only from XAML:
this.NavigationService.Content = nextPage;
this.NavigationService.Source = new Uri("photopage.xaml", UriKind.Relative);
Hyperlink element is used to link to XAML pages:
<TextBlock>
Click
<Hyperlink NavigateUri="photopage.xaml">here</Hyperlink> to view the photo.
</TextBlock>
Hyperlinks can also handle Click events, navigate from HTML to WPF, use TargetName to update a Frame, or use # and any named element in a page.
Using Journal
The Journal provides the logic behind Back and Forward navigation. Internally it uses two stacks; Back/Fwd moves pages between stacks. Any other action empties the Forward stack.
π Definition β Journal: The history system that tracks navigation and enables Back/Forward functionality.
Containers have GoBack(), GoForward(), CanGoBack, and CanGoForward properties to avoid exceptions. NavigationWindow always has a journal, but Frame's journal depends on JournalOwnership:
- OwnsJournal: Frame owns its journal
- UsesParentJournal: Uses parent's journal
- Automatic: Uses parent journal when hosted in a window or frame
When Frame has a journal, it shows Back/Forward buttons, but this can be hidden with NavigationUIVisibility="Hidden".
Navigation with URI or Hyperlink always creates a new instance. You can control instance creation when calling Navigate with Page, or use the JournalEntry.KeepAlive attached property to preserve state across Back/Forward navigation. RemoveFromJournal means a page is not stored in the journal.
Custom Content State
For application-specific features like undo/redo, navigation containers support AddBackEntry with a custom CustomContentState abstract class that must define a Replay method. Optionally, JournalEntryName can be set.
Example from photo gallery for undoable image rotation:
[Serializable]
class RotateState : CustomContentState
{
FrameworkElement element;
double rotation;
public RotateState(FrameworkElement element, double rotation)
{
this.element = element;
this.rotation = rotation;
}
public override string JournalEntryName
{
get { return "Rotate " + rotation + "Β°"; }
}
public override void Replay(NavigationService navigationService, NavigationMode mode)
{
// Rotate the element by the specified amount
element.LayoutTransform = new RotateTransform(rotation);
}
}
Navigation Events
NavigationStopped is an event called instead of LoadCompleted if an error occurs or navigation is cancelled. These events are also defined in the Application class to handle navigation for any container. HTML-to-HTML navigation is not stored in the journal and raises no events.
Passing Data Between Pages
Data can be passed between pages using several methods:
- Using Navigate overload with extra object parameter:
int photoId = 10;
this.NavigationService.Navigate(nextPage, photoId);
The target page receives it in LoadCompleted:
void container_LoadCompleted(object sender, NavigationEventArgs e)
{
if (e.ExtraData != null)
LoadPhoto((int)e.ExtraData);
}
- Using constructor parameters:
public PhotoPage(int id)
{
LoadPhoto(id);
}
Then navigate by instance:
PhotoPage nextPage = new PhotoPage(photoId);
this.NavigationService.Navigate(nextPage);
- Using Application.Properties:
Application.Properties["photoId"] = 10;
this.NavigationService.Navigate(/* */);
if (Application.Properties["photoId"] != null)
LoadPhoto((int)Application.Properties["photoId"]);
PageFunction for Returning Data
PageFunction acts like a function that can return data to the calling page. It is a generic class that specifies the return type.
<PageFunction
x:TypeArguments="sys:String"
x:Class="myproject.PageFunction1"
Title="PageFunction1">
<Grid>
</Grid>
</PageFunction>
Usage:
PageFunction1 nextPage = new PageFunction1<string>();
this.NavigationService.Navigate(nextPage);
nextPage.Return += new ReturnEventHandler<string>(nextPage_Return);
Handling the return:
void nextPage_Return(object sender, ReturnEventArgs<string> e)
{
string returnValue = e.Result;
}
Calling OnReturn(new ReturnEventArgs<string>("the data")); returns data from the PageFunction.
β Key Takeaways
Navigation containers (NavigationWindow and Frame) use Pages as content units and provide a journal system for Back/Forward navigation. The NavigationService class enables programmatic control of navigation regardless of the container type. Data can be passed between pages through Navigate overloads with extra data, constructor parameters, or Application.Properties. For returning data, PageFunction provides a clean mechanism similar to function calls. Custom content states via CustomContentState enable application-specific journal entries for undo/redo functionality.
π§ Quick Revision Questions
- What are the three main ways to perform navigation in WPF navigation applications?
- How does the JournalOwnership property affect a Frame's behavior regarding Back/Forward buttons?
- What is the difference between NavigationWindow and Frame in terms of default UI?
- How can you pass data from one page to another when navigating, and what events can the target page use to receive that data?
- What is the purpose of the CustomContentState class and how does the Replay method work in the context of the journal system?
π Lecture 27 β XAML Browser Applications & Resources
π Overview: This lecture explores XAML Browser Applications (XBAPs) for delivering WPF content in web browsers with partial-trust security. It also covers WPF resource management, including binary and logical resources, enabling efficient deployment and localization of application assets.
ποΈ Topics Covered
The lecture covers XBAP architecture and deployment, partial-trust restrictions and security implications, clickonce caching and navigation integration, full-trust browser app configuration, downloading files on demand using application deployment API, and WPF resource types including binary resources, content files, and pack URIs for accessing embedded assets.
π Lecture Summary
XAML Browser Applications (XBAPs)
XBAPs are partial-trust WPF applications delivered in a browser, similar to Silverlight but with some limitations. Not all WPF features are available by default, navigation is integrated into the browser, and deployment differs from desktop apps. In Visual Studio, you create a WPF Browser Application, design UI in a Page, compile and runβthese are online-only ClickOnce applications with special WPF handling.
β οΈ Security Restriction: Partially trusted code cannot access certain APIs, such as:
AddFavorite(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures));
This throws an exception because it requires FileIOPermission, which is not granted by default.
π Definition β BrowserInteropHelper.IsBrowserHosted: A property that checks whether the current application is running as an XBAP in a browser.
π Example: Using OpenFileDialog in an XBAP:
string fileContents = null;
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == true)
{
using (Stream s = ofd.OpenFile())
using (StreamReader sr = new StreamReader(s))
{
fileContents = sr.ReadToEnd();
}
}
Available capabilities despite partial trust: Rich text and media, isolated storage (up to 512KB), arbitrary files on host web server, browser file open dialog for local files.
Parameter passing methods:
- BrowserInteropHelper.Source β retrieves the complete URL
- Application.GetCookie β retrieves browser cookies
π‘ Why this matters: Any assembly marked with AllowPartiallyTrustedCallers and placed in the GAC can be called by partial-trust code, which can be a security loophole.
Full-Trust Browser Apps
To create a full-trust XBAP, modify the project file:
Change:
<TargetZone>Internet</TargetZone>
To:
<TargetZone>Custom</TargetZone>
In the ClickOnce application manifest, add:
<PermissionSet class="System.Security.PermissionSet" version="1"
ID="Custom" SameSite="site" Unrestricted="true"/>
Integrated Navigation: IE7 and later merge the journal for a streamlined interface. If the XBAP appears in an iframe, there is still a separate navigation bar.
Publishing: Use VS Publishing Wizard or Mage tool in SDK, copy files to a web server configured to serve them. Users can install by navigating to a URL without security prompts if standard permissions are sufficient.
Downloading Files on Demand
Files can be assigned to a download group in Visual Studio under Publish β Application Files in project properties. Use the System.Deployment.Application API to prompt download and receive notifications.
π Example: Load a group and navigate to Page2:
public partial class Page1 : Page
{
public Page1() { InitializeComponent(); }
protected override void OnInitialized(EventArgs e)
{
base.OnInitialized(e);
if (ApplicationDeployment.IsNetworkDeployed)
{
ApplicationDeployment.CurrentDeployment.DownloadFileGroupCompleted +=
delegate {
Dispatcher.BeginInvoke(DispatcherPriority.Send,
new DispatcherOperationCallback(GoToPage2), null);
};
ApplicationDeployment.CurrentDeployment.DownloadFileGroupAsync("mygroup");
}
else
{
GoToPage2(null);
}
}
private object GoToPage2(object o)
{
return NavigationService.Navigate(new Uri("Page2.xaml", UriKind.Relative));
}
}
Loose XAML is sometimes more powerful than HTML for delivering content.
WPF Resources
WPF has two types of resources:
- Binary resources β what the .NET Framework considers a resource (including compiled XAML)
- Logical resources β XAML resource dictionaries
Binary resources can be:
- Embedded in assembly
- Loose files (may or may not be known at compile time)
- Localizable or non-localizable
π Definition β Build Action: Resource vs Content:
- Resource: Embedded in the assembly binary
- Content: Loose file deployed alongside the assembly
- β Do not use EmbeddedResource β WPF doesn't fully support it
π Pack URIs for accessing resources:
pack://application:,,,/logo.jpgβ for embedded resourcespack://siteoforigin:,,,/slideshow.gifβ for content files at the site of origin
π Example: Assigning binary resources in XAML:
<Image Height="21" Source="previous.gif"/>
Or explicitly using pack URI:
<Image Height="21" Source="pack://siteoforigin:,,,/slideshow.gif"/>
π Example: From procedural code:
Image image = new Image();
image.Source = new BitmapImage(new Uri("pack://application:,,,/logo.jpg"));
π‘ Why this matters: Subfolders can be used for embedded resources, but from procedural code, you cannot use XAML shortcutsβyou must use full pack URIs.
β Key Takeaways
XBAPs deliver WPF content in browsers with partial-trust restrictions, requiring careful API selection to avoid security exceptionsβuse isolated storage (512KB limit) and browser dialogs for file access. Full-trust XBAPs require modifying project settings and adding unrestricted permission sets to the manifest. Files can be downloaded on demand using the ApplicationDeployment API with download groups for efficient loading. WPF resources include binary resources (embedded or content) accessed via pack URIsβembed for localization, use content for loose files. Always use Build Action "Resource" or "Content" (not "EmbeddedResource") and understand pack URI syntax for both XAML and procedural code access.
π§ Quick Revision Questions
- What property checks whether a WPF application is running as an XBAP in a browser?
- How much isolated storage is available by default in a partial-trust XBAP?
- What XML changes are required to convert an XBAP from partial-trust to full-trust?
- Which namespace contains the ApplicationDeployment class for downloading file groups?
- What is the difference between "Content" and "Resource" build actions for WPF binary resources?