Windows Presentation Foundation

Size: px
Start display at page:

Download "Windows Presentation Foundation"

Transcription

1 .NET Programming Windows Presentation Foundation WPF C. Anderson, Essential Windows Presentation Foundation, Addison-Wesley, 2007 M. MacDonald, Pro WPF in C# 2008, 2nd Ed., Apress, 2008 S. Noble et al., WPF Recipes in C# 2008, Apress, 2008 A. Nathan, Windows Presentation Foundation Unleashed, Sams, 2007 C. Petzold, Applications = Code + Markup: A Guide to the Microsoft Windows Presentation Foundation, Microsoft Press, 2006 MSDN

2 Contents Overview Applications Controls Layout Graphics and multimedia Data 2

3 3 Overview

4 Principles of WPF Build a platform for rich presentation Build a programmable platform Build a declarative platform Integrate UI, documents, and media Incorporate the best of the Web, and the best of Windows Integrate developers and designers 4

5 WPF History A new team formed by Microsoft to build a unified presentation platform that could eventually replace User32/GDI32, Visual Basic, DHTML, and Windows Forms The Avalon project announced at Professional Developer Conference WPF released as a part of the.net Framework 3.0 VS 2005 Extensions for.net 3.0 (CTP) WPF included with Windows Vista.NET Framework 3.5 Expression Blend 1.0 VS 2008 & VS WPF Designer WPF 3.5 SP1 (included in.net 3.5 SP1) 5

6 Supported Systems WPF is included with: Windows Vista Windows Server 2008 It is also available for: Windows XP SP2 Windows Server

7 WPF Features Graphical Services All graphics are Direct3D applications More advanced graphical features Using Graphics Processing Unit of a graphics card Vector-based graphics with lossless scaling 3D model rendering Interoperability WPF can be used inside Win32 code or WPF can use Win32 code Windows Forms interoperability is possible using the ElementHost and WindowsFormsHost classes Annotations WPF only provides the capability for creating, storing and managing annotations Annotations can be applied on a per-object basis, for objects in a Document or FlowDocument 7

8 WPF Features cont. Media Services 2D graphics with built-in set of brushes, pens, geometries, and transforms 3D capabilities as a subset of the full feature Direct3D's set Support for most common image formats Support for Windows Imaging Component that allows to write image codecs Support for WMF, MPEG and some AVI films Support for Windows Media Player codecs Animations Time-based animations Animations can be triggered by other external events, including user action Animation effects can be defined on a per-object basis Set of predefined animation effects 8

9 WPF Features cont. Data binding Three types of data binding: One time: the client ignores updates on the server One way: the client has read-only access to data Two way: the client can read from and write data to the server LINQ queries can act as data sources User interface A set of built-in controls A control's template can be overridden to completely change its visual appearance Applications do not have to be bothered with repainting the display Documents Support for XML Paper Specification documents Supports reading and writing paginated documents using Open Packaging Convention 9

10 WPF Features cont. Text Support for OpenType, TrueType, and OpenType CFF fonts WPF handles texts in Unicode Independent of global settings, such as system locale Built-in features: spell checking, automatic line spacing, enhanced international text, language-guided line breaking, hyphenation, justification, bitmap effects, transforms, and text effects such as shadows, blur, glow, rotation etc. Support for animated text (both animated glyphs and real-time changes in postion, size, colour, and opacity) Accessibility Microsoft UI Automation 10

11 XAML Extensible Application Markup Language (XAML) is a markup language for declarative application programming The developer (or designer) describes the behaviour and integration of components without the use of procedural programming Using XAML to develop user interfaces allows for separation of model and view However, all elements of WPF may be coded e.g. in C# The XAML code can ultimately be compiled into a managed assembly in the same way all.net languages are 11 XAML is not specific to WPF (or even.net), however, it has been introduced as integral part of WPF

12 Architecture PresentationFramework End-user presentation features (including layouts, animations, and data-binding) PresentationCore A managed wrapper for MIL It implements the core services milcore Media Integration Layer It interfaces directly with DirectX It is a native component 12

13 System.Threading.DispatcherObject Most objects in WPF derive from DispatcherObject It provides the basic constructs for dealing with concurrency and threading WPF is based on a messaging system implemented by the dispatcher The WPF dispatcher uses User32 messages for performing cross thread calls 13 All WPF applications start with two threads: one for managing the UI and another background thread for handling rendering and repainting

14 System.Windows.DependencyObject One of the primary architectural philosophies used in building WPF was a preference for properties over methods or events Properties are declarative and allow to more easily specify intent instead of action WPF provides a richer (than exists in CLR) property system, derived from the DependencyObject type Currently, the set of expressions supported is closed WPF properties support change notifications, which invoke bound behaviours whenever some property of some element is changed Custom behaviors can be used to propagate a property change notification across a set of WPF objects 14

15 System.Windows.Media.Visual The Visual class provides for building a tree of visual objects, each optionally containing drawing instructions and metadata about how to render those instructions (clipping, transformation, etc.) It is the point of connection between these two subsystems, the managed API and the unmanaged milcore WPF displays data by traversing the unmanaged data structures managed by the milcore The entire tree of visuals and drawing instructions is cached WPF uses a retained rendering system Instead of clipping each component, each component is asked to render from the back to the front of the display It allows to have complex, partially transparent shapes 15

16 System.Windows.UIElement UIElement defines core subsystems including Layout, Input, and Events Layout is a core concept in WPF At the UIElement level, the basic contract for layout is introduced a two phase model with Measure and Arrange passes Input originates as a signal on a kernel mode device driver It gets routed to the correct process and thread through an intricate process involving the Windows kernel and User32 Once the User32 message corresponding to the input is routed to WPF, it is converted into a WPF raw input message and sent to the dispatcher WPF allows for raw input events to be converted to multiple actual events 16

17 System.Windows.FrameworkElement It introduces a set of policies and customizations on the subsystems introduced in lower layers of WPF The primary policy introduced by FrameworkElement is around application layout It also introduces a set of new subsystems The data binding subsystem allows to bind properties to a piece of data WPF has full support for property binding, transformation, and list binding Data templates allow you to declaratively specify how a piece of data should be visualized Styling is really a lightweight form of data binding It allows to bind a set of properties from a shared definition to one or more instances of an element 17

18 System.Windows.Controls.Control Control s most significant feature is templating Templating allows a control to describe it s rendering in a parameterized, declarative manner A common aspect of the data model of controls is the content model E.g., content for a button can either be a simple string, a complex data object, or an entire element tree In the case of a data object, the data template is used to construct a display 18

19 Events Event handler can be attached either using the XAML markup or C# code <Image Name="FionaImage" Margin="5" Source="Images/Fiona_67x77.gif" MouseEnter="FionaImage_MouseEnter" MouseLeave="FionaImage_MouseLeave"/> FionaImage.MouseEnter += new MouseEventHandler(FionaImage_MouseEnter); FionaImage.MouseLeave += FionaImage_MouseLeave; 19

20 Events Routing There are three types of events differ by a way of routing them between controls and their containers: Direct events originate in one element and don't pass to any other examples: MouseEnter, MouseLeave Bubbling events travel up the containment hierarchy example: MouseDown it is raised first by the element that is clicked, next it s raised by that element s parent and so on Tunneling events travel down the containment hierarchy example: PreviewKeyDown allows to intercept a key press first at the window level WPF usually defines bubbling and tunneling events in pairs, e.g. for the MouseUp bubbling event there exists the PreviewMouseUp tunneling event (all tunneling events are named using the 'Preview' word) Events in the pair share the same instance of the RoutedEventArgs class, so if the tunneling event is marked as handled, the bubbling event will not occur 20

21 The RoutedEventArgs Class All WPF event argument classes inherit from RoutedEventArgs There are four properties of the RoutedEventArgs class: Source the object that raised the event OriginalSource the object that originally raised the event usually the same as the Source object, but in some cases it goes deeper in the object tree RoutedEvent a special object for the event triggered by the event handler Handled when set to true, the event does not travel any further the containment hierarchy 21

22 Keyboard Input The following keyboard events are available for all elements: PreviewKeyDown, KeyDown, PreviewTextInput, TextInput, PreviewKeyUp, KeyUp Focus A control is able to accept the focus, only when its Focusable property is set to true The TabIndex property can be used to order controls from the point of view of the focus The KeyboardDevice property of the KeyboardEventArgs class allows to check the state of keyboard modifiers keys (Shift, Ctrl, etc.) in the moment of raising the event The current state of the keyboard can be discovered using the Keyboard class and its static properties and methods 22

23 Mouse Input The following mouse events are available for all elements: MouseEnter, MouseLeave MouseLeftButtonDown, MouseLeftButtonUp, MouseRightButtonDown, MouseRightButtonUp, and their corresponding Preview... tunneling events The Control class adds the following events: MouseDoubleClick, PreviewMouseDoubleClick The Mouse.Capture method allows for an element to receive mouse events even if they occur after the mouse has moved off the element The DragDrop.DoDragDrop method and the element's: AllowDrop property and Drop event allow to implement custom drawg and drop operation between elements 23

24 Commanding WPF allows you to define tasks known as command and connect controls them so there is no need to write repetitive event handling code The command feature manages the state of your user interface by automatically disabling controls when the linked commands aren t available The WPF command model consists of the following parts: The command is the action to be executed The command source is the object which invokes the command The command target is the object that the command is being executed on The command binding is the object which maps the command logic to the command 24

25 Commands Commands in WPF are created by implementing the ICommand interface This interface contains two methods: Execute and CanExecute, and an event CanExecuteChanged The RoutedCommand class is the WPF implementation of ICommand with support for bubbling and tunneling WPF supplies a set of common routed commands spread across 5 classes: MediaCommands, ApplicationCommands, NavigationCommands, ComponentCommands, and EditingCommands Custom commands can be easily created by creating objects of the RoutedCommand or RoutedUICommand classes It is also possible to create a custom class implementing the ICommand interface 25

26 Command Sources A command source is the object which invokes the command Examples of command sources are MenuItem, Button, and KeyGesture Command sources in WPF generally implement the ICommandSource interface This interface exposes 3 properties: Command, CommandTarget, and CommandParameter The following classes implement ICommandSource: ButtonBase, MenuItem, Hyperlink, and InputBinding Two types of input gestures in WPF are the KeyGesture and MouseGesture Typically, a command source will listen to the CanExecuteChanged event. 26

27 CommandBinding A CommandBinding associates a command with the event handlers that implement the command It contains a Command property, and PreviewExecuted, Executed, PreviewCanExecute, and CanExecute events A CommandBinding is attached to a specific object, such as the root Window of the application or a control In some situations the CommandBinding is attached to the command target itself, such as with the TextBox class and the Cut, Copy, and Paste commands In most cases it is more convenient to attach the CommandBinding to an ancestor of the command target, especially if the same CommandBinding can be used for multiple command targets 27

28 <Window.CommandBindings> <CommandBinding Command="ApplicationCommands.Stop" Commanding Executed="Stop_Executed" Example CanExecute="Stop_CanExecute"/> </Window.CommandBindings> <Window.InputBindings> <KeyBinding Key="S" Modifiers="Control" Command="ApplicationCommands.Stop"/> </Window.InputBindings> <StackPanel> <Menu> <MenuItem Name="stopMenuItem" Header="Stop menu item" Command="ApplicationCommands.Stop" /> </Menu> <Button Name="stopButton" Command="ApplicationCommands.Stop">Stop button</button> <CheckBox Name="allowStopCheckBox">Allow stop</checkbox> </StackPanel> Windows Presentation Foundation private void Stop_Executed(object sender, ExecutedRoutedEventArgs e) { MessageBox.Show("Stop executed!"); } private void Stop_CanExecute(object sender, CanExecuteRoutedEventArgs e) { e.canexecute = (allowstopcheckbox!= null)? allowstopcheckbox.ischecked.value : false; Krzysztof } Mossakowski 28

29 Command Target The command target is the element on which the command is executed In WPF the CommandTarget property on ICommandSource is only applicable when the ICommand is a RoutedCommand The command source can explicitly set the command target If the command target is not defined, the element with keyboard focus will be used as the command target For example, it allows to work the Paste menu item with currently being edited TextBox 29

30 Tools for WPF Microsoft Visual Studio 2008 WPF Designer Microsoft Expression Blend A designer-oriented tool that provides a canvas for the creation of WPF applications with 2D and 3D graphics, text and forms content It generates XAML that may be exported into other tools Microsoft Expression Design A bitmap and 2D-vector graphics tool with export to XAML Other designers: Aurora XAML Designer ZAM 3D 30

31 Tools for WPF cont. A set of WPF tools: ViewerSvg, ReaderSvg, Paste2Xaml, ReaderWmf, ZoomPanel, Viewer3ds, Reader3ds Snoop XAML Power Toys Performance Profiling Tools for WPF (available in Windows SDK for Windows Server 2008 and.net Framework 3.5) Shazzam WPF Pixel Shader Utility 31

32 Converters & Exporters for XAML 32 Maya To XAML XAML Exporter for Blender Online converter from 3ds to xaml Fireworks to XAML Exporter Adobe Illustrator to XAML Export XamlXporter for Illustrator Adobe Flash to XAML Conversion Tool Swf to Xaml Converter Lightwave to Xaml ViewerSvg - svg to xaml converter VisioExportToXAML

33 33 Applications

34 Application Class The Application object is responsible for managing the lifetime of the application, tracking the visible windows, dispensing resources, and managing the global state of the application A WPF application logically starts executing when the Run method is invoked on an instance of the Application object using System; using System.Windows; namespace WpfApplication1 { static class Program { [STAThread] static void Main() { Application app = new Application(); Window w = new Window(); w.title = "Hello World"; w.show(); app.run(); } } } 34

35 Application's Lifetime 1. Application object is constructed 2. Run method is called 3. Application.Startup event is raised Using the Startup event is a preferred place for application initialization (as opposed for the constructor) 4. User code constructs one or more Window objects 5. Application.Shutdown method is called 6. Application.Exit event is raised 7. Run method completes 35

36 Error Handling The Application.DispatcherUnhandledException event is raised when the dispatcher sees an unhandled exception The DispatcherUnhandledExceptionEventArgs.Handled flag indicates if the exception should be ignored and the application should continue to run <Application [...] DispatcherUnhandledException="App_UnhandledException"> </Application> public partial class App : Application { private void App_UnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) { using (StreamWriter errorlog = new StreamWriter("c:\\error.log", true)) { " + DateTime.Now.ToString()); errorlog.writeline(e.exception.tostring()); } e.handled = true; } } 36

37 Application's State The application object is available globally using the Application.Current static property The Application.Properties is a dictionary of any custom data stored at the level of the application 37 Application.Current.Properties["LastError"] = e.exception; object lasterror = Application.Current.Properties["LastError"]; if (lasterror!= null && lasterror is DivideByZeroException) { }

38 Resources Types Content Copies each resource to the directory of the application Can be used in markup Available by Application.GetContentStream Resource Embeds each resource in a common resource in the application Can be used in markup Supports localized loading Available by Application.GetResourceStream EmbeddedResource Embeds each resource in the application separately Cannot be used in markup Supports localized loading Available by Assembly.GetManifestResourceStream 38

39 Windows The base type for all windows in WPF is System.Windows.Window Window is a control designed for hosting top-level content in an application Value of the Application.ShutdownModeValue property determines the way to close the application: OnLastWindowClose OnMainWindowClose (using the MainWindow property) OnExplicitShutdown (using the Shutdown method) All the currently open windows can be enumerated using the Application.Windows property 39

40 Windows Operations Displaying: Show, Visibility to avoid displaying a window on a Alt-Tab window, set its Owner property ShowDialog to display the dialog modally Sizing and position WindowStartupLocation SizeToContent Left, Top, Width, Height ResizeMode MinWidth, MaxWidth, MinHeight, MaxHeight 40

41 Window's Lifetime 1. Constructor is called 2. Window.Initialized event is raised 3. Window.Activated event is raised Activated and Deactivated occur many times over the life of a window as the user switches between multiple windows running on the system 4. Window.Loaded event is raised 5. Window.ContentRendered event is raised 6. User interacts with the window 7. Window.Closing event is raised This event can be cancelled 8. Window.Unloaded event is raised 9. Window.Closed event is raised 41

42 Navigation and Pages WPF has a built-in navigation framework There are 3 basic concepts of this framework: Navigation host NavigationWindow is the default host; it derives from Window and adds a default navigation UI Navigable content In WPF it is possible to navigate to any content, e.g. data objects, primitive types like strings, or pages Page is a convenient class that has helper methods for making content easier to navigate Journal It is responsible for tracking the navigation actions (including back and forward) 42

43 Navigation Example 43 NavigationWindow navwnd = new NavigationWindow(); navwnd.navigate(new Page1()); navwnd.show(); <Page x:class="wpfapplication1.page1" xmlns=" xmlns:x=" Title="Page1"> <Grid> <TextBlock Name="textBlock1"> <Label>This is Page1.</Label> <Hyperlink NavigateUri="Page2.xaml">Go to Page2</Hyperlink> </TextBlock> </Grid> </Page> <Page x:class="wpfapplication1.page2" xmlns=" xmlns:x=" Title="Page2"> <Grid> <Label>This is Page2.</Label> </Grid> </Page>

44 NavigationService NavigationService encapsulates the ability to download content within the context of a browser-style navigation It is available as a property in the following classes: NavigationWindow Frame Page Available events: 44

45 Page Functions The PageFunction<T> class represents a special type of page that allows you to treat navigation to a page in a similar fashion to calling a method To enable function call semantics, PageFunction<T> provides the following capabilities: When the page function has finished processing, the page function code calls OnReturn to return to the calling page OnReturn accepts a ReturnEventArgs<T> parameter, which can be used to return a value by settings the Result property. Otherwise, null can be passed to OnReturn to signify no value is returned To detect when a page function has returned, the calling page can handle the Return event The calling page can retrieve the returned value from the ReturnEventArgs<T> object that is passed to the Return event handler. 45

46 PageFunction Example public partial class Page1 : Page { public Page1() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { Page2 page2 = new Page2(); page2.return += new ReturnEventHandler<string>(page2_Return); NavigationService.Navigate(page2); } void page2_return(object sender, ReturnEventArgs<string> e) { valuelabel.content = e.result; <PageFunction } x:class="wpfapplication1.page2" } xmlns=" xmlns:x=" xmlns:sys="clr-namespace:system;assembly=mscorlib" x:typearguments="sys:string" Title="Page2"> <Grid> <StackPanel> <Label>This is Page2. Write value:</label> <TextBox Name="valueTextBox"></TextBox> <Button Name="returnButton" Click="returnButton_Click">Return</Button> </StackPanel> </Grid> </PageFunction> private void returnbutton_click(object sender, RoutedEventArgs e) { OnReturn(new ReturnEventArgs<string>(valueTextBox.Text)); } 46

47 Hosting Applications in a Browser WPF applications support running either in a stand-alone window or inside the browser XAML Browser Applications (XBAPs) allow us to run an application inside the browser frame They have no permanent presence on the user s machine They normally run in a.net-enforced partial-trust sandbox To enable the application to be hosted in a browser, it must be signed using a minifest The XBAP file (which can be opened in a browser) is an XML file containing deployment information, exactly the same as the deployment manifest used for desktop applications Also XAML files, when not using code behind, can be directly opened in a browser 47

48 XBAP Example <Application x:class="wpfbrowserapplication1.app" xmlns=" xmlns:x=" StartupUri="Page1.xaml"> </Application> 48 <?xml version="1.0" encoding="utf-8"?> <asmv1:assembly manifestversion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1" xmlns:asmv1="urn:schemas-microsoft-com:asm.v1" xmlns:asmv2="urn:schemas-microsoft-com:asm.v2" xmlns:xsi=" <assemblyidentity version=" " name="myapplication.app"/> <trustinfo xmlns="urn:schemas-microsoft-com:asm.v2"> <security> <applicationrequestminimum> <defaultassemblyrequest permissionsetreference="custom" /> <PermissionSet class="system.security.permissionset" version="1" ID="Custom" SameSite="site" /> </applicationrequestminimum> <requestedprivileges xmlns="urn:schemas-microsoft-com:asm.v3"> <requestedexecutionlevel level="asinvoker" uiaccess="false" /> </requestedprivileges> </security> </trustinfo> </asmv1:assembly>

49 Example of Hosting in a Browser 49 If the browser doesn t support the new navigation APIs, the root browser window will automatically display a navigation UI

50 50 Controls

51 Content Models There are 4 content models used by controls: ContentControl contains a single item used by: Button, ButtonBase, CheckBox, ComboBoxItem, ContentControl, Frame, GridViewColumnHeader, GroupItem, Label, ListBoxItem, ListViewItem, NavigationWindow, RadioButton, RepeatButton, ScrollViewer, StatusBarItem, ToggleButton, ToolTip, UserControl, Window HeaderedContentControl contains a header and a single item Expander, GroupBox, TabItem ItemsControl contains a collection of items ComboBox, ContextMenu, ListBox, ListView, Menu, StatusBar, TabControl, TreeView HeaderedItemsControl contains a header and a collection of items MenuItem, ToolBar, TreeViewItem 51

52 Content The ContentControl class represents a control with a single piece of content The ContentPresenter class is responsible for displaying the content of a ContentControl; it uses the following algorithm: 1. If Content is of type UIElement, then add it to the display tree 2. If ContentTemplate is set, use that to create a UIElement instance and add it to the display tree 3. If ContentTemplateSelector is set, use that to find a template, use the template to create a UIElement instance, and add it to the display tree 4. If the data type of Content has a data template associated with it, use that to create a UIElement instance 5. If the data type of Content has a TypeConverter instance associated with it that can convert to type UIElement, convert Content and add it to the display tree 6. If the data type of Content has a TypeConverter instance associated with it that can convert to a string, wrap Content in TextBlock and add it to the display tree 7. Finally, call ToString on Cotent, wrap it in TextBlock, and add it to the display tree 52

53 Content Example 53 <Window x:class="wpfapplication1.window2" xmlns=" xmlns:x=" Title="Window2" Height="300" Width="300"> <Grid> <ListBox Name="listBox1" VerticalAlignment="Stretch"> <ListBoxItem> The first item </ListBoxItem> <ListBoxItem> <Rectangle Fill="Yellow" Height="20" Width="20"></Rectangle> </ListBoxItem> <ListBoxItem> <Image Source="Images/Fiona_67x77.gif"></Image> </ListBoxItem> <ListBoxItem> <StackPanel Orientation="Horizontal"> <TextBlock>The fourth item</textblock> <Rectangle Fill="Yellow" Height="20" Width="20"></Rectangle> <Image Source="Images/Fiona_67x77.gif"></Image> </StackPanel> </ListBoxItem> </ListBox> </Grid> </Window>

54 Content Example cont. 54

55 Templates Templates are a factory for creating a new display tree There are 2 types of templates: ControlTemplate creates a display tree for a control DataTemplate creates a display tree for a piece of data The structure and appearance of a control can be modified by defining a new ControlTemplate for the control If no own ControlTemplate is created for a control, the default template that matches the system theme will be used There is no way to replace only part of the visual tree of a control - a complete ControlTemplate must be provided A template's trigger sets properties or starts actions such as animation when a property value changes or when an event is raised 55

56 <Window x:class="wpfapplication1.windowwithbutton" Windows Presentation Foundation xmlns=" xmlns:x=" Template Title="WindowWithButton" Example Height="80" Width="150"> <Button> <Button.Template> <ControlTemplate TargetType='{x:Type Button}'> <Border Name="MyBorder" CornerRadius='4' BorderThickness='1'> <Border.BorderBrush> <SolidColorBrush Color="Black"/> </Border.BorderBrush> <Border.Background> <LinearGradientBrush EndPoint='0,1'> <LinearGradientBrush.GradientStops> <GradientStop Offset='0' Color='#FF777777' /> <GradientStop Offset='1' Color='#FFFFFFFF' /> </LinearGradientBrush.GradientStops> </LinearGradientBrush> </Border.Background> <ContentPresenter HorizontalAlignment='Center' VerticalAlignment='Center' /> </Border> <ControlTemplate.Triggers> <Trigger Property="Button.IsPressed" Value="True"> <Setter TargetName="MyBorder" Property="Border.Background" Value="{DynamicResource {x:static SystemColors.ControlDarkBrushKey}}" /> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Button.Template> This is a button Krzysztof </Button> Mossakowski </Window> 56

57 Template Binding Template binding allows to add parameters to templates Parameters allow to customize a template for a control by using properties <ControlTemplate x:key="mybuttontemplate" TargetType='{x:Type Button}'> <Border Name="MyBorder" CornerRadius='4' BorderThickness='{TemplateBinding Property=BorderThickness}' BorderBrush='{TemplateBinding Property=BorderBrush}' Background='{TemplateBinding Property=Background}'> <ContentPresenter /> </Border> <ControlTemplate.Triggers> <Trigger Property="Button.IsPressed" Value="True"> <Setter TargetName="MyBorder" Property="Border.Background" Value="{DynamicResource {x:static SystemColors.ControlDarkBrushKey}}" /> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> <Button Template="{StaticResource MyButtonTemplate}" Background="Yellow" > This is a button </Button> <Button Template="{StaticResource MyButtonTemplate}" BorderBrush="Cyan"> This is another button </Button> 57

58 Buttons ButtonBase Button ToggleButton CheckBox RadioButton 58 <StackPanel Orientation='Horizontal'> <Button Margin='5' VerticalAlignment='Top'>Click</Button> <StackPanel Margin='5' VerticalAlignment='Top'> <CheckBox IsChecked='True'>Click</CheckBox> <CheckBox IsChecked='False'>Click</CheckBox> <CheckBox IsChecked='{x:Null}'>Click</CheckBox> </StackPanel> <StackPanel Margin='5' VerticalAlignment='Top'> <RadioButton>Click</RadioButton> <RadioButton IsChecked='True'>Click</RadioButton> <RadioButton>Click</RadioButton> </StackPanel> </StackPanel>

59 Lists ListBox and ComboBox As the source for a list, any type that implements IEnumerable can be used for the ItemsSource property In.NET 3.0 a new ObservableCollection<T> collection was provided The ItemsPanel property can provide a template for creating the layout panel that will be used to display the items in the list ItemsPanel takes ItemsPanelTemplate, which requires that the template build a panel It allows to use custom layout for a ListBox or ComboBox 59

60 <StackPanel> <ComboBox> Windows Presentation Foundation ListBox <ComboBox.ItemsPanel> and ComboBox Example <ItemsPanelTemplate> <UniformGrid Columns='2'/> </ItemsPanelTemplate> </ComboBox.ItemsPanel> <ComboBoxItem>First</ComboBoxItem> <ComboBoxItem>Second</ComboBoxItem> <ComboBoxItem>Third</ComboBoxItem> <ComboBoxItem>Fourth</ComboBoxItem> </ComboBox> <Rectangle Height="100"></Rectangle> <ListBox> <ListBox.ItemsPanel> <ItemsPanelTemplate> <UniformGrid Columns='2'/> </ItemsPanelTemplate> </ListBox.ItemsPanel> <ListBoxItem>First</ListBoxItem> <ListBoxItem>Second</ListBoxItem> <ListBoxItem>Third</ListBoxItem> <ListBoxItem>Fourth</ListBoxItem> </ListBox> <ListBox> <ListBoxItem>First</ListBoxItem> <ListBoxItem>Second</ListBoxItem> <ListBoxItem>Third</ListBoxItem> </ListBox> </StackPanel> 60

61 Lists cont. The ListView control derives from the ListBox class It adds the ability to separate view properties from control properties To specify a view mode for the content of a ListView control, the View property must be set One view mode that WPF provides is GridView, which displays a collection of data items in a table that has customizable columns <StackPanel> <ListView> <ListViewItem>First</ListViewItem> <ListViewItem>Second</ListViewItem> <ListViewItem>Third</ListViewItem> <ListViewItem>Fourth</ListViewItem> <ListView.View> <GridView> <GridViewColumn Header="My Header" Width="200"/> </GridView> </ListView.View> </ListView> </StackPanel> 61

62 Lists cont. The TreeView control provides a way to display information in a hierarchical structure by using collapsible nodes The TreeView control contains a hierarchy of TreeViewItem controls A TreeViewItem control is a HeaderedItemsControl that has a Header and an Items collection <TreeView> <TreeViewItem Header="1" IsExpanded="True"> <TreeViewItem> <TreeViewItem.Header> <DockPanel> <CheckBox/> <TextBlock>11</TextBlock> </DockPanel> </TreeViewItem.Header> </TreeViewItem> <TreeViewItem Header="12"> <TreeViewItem Header="121"/> <TreeViewItem Header="122"/> </TreeViewItem> </TreeViewItem> </TreeView> 62

63 Using Templates for Lists <Window x:class="wpfapplication1.ctrl_templatelist" xmlns=" xmlns:x=" xmlns:sys="clr-namespace:system;assembly=mscorlib" Title="Ctrl_TemplateList" Height="300" Width="300"> <Grid> <ListBox> <ListBox.ItemContainerStyle> <Style TargetType='{x:Type ListBoxItem}'> <Setter Property='Template'> <Setter.Value> <ControlTemplate TargetType='{x:Type ListBoxItem}'> <RadioButton IsChecked='{Binding Path=IsSelected,RelativeSource={RelativeSource TemplatedParent}}' Content='{TemplateBinding Property=Content}' /> </ControlTemplate> </Setter.Value> </Setter> </Style> </ListBox.ItemContainerStyle> <sys:string>first</sys:string> <sys:string>second</sys:string> <sys:string>third</sys:string> <sys:string>fourth</sys:string> </ListBox> </Grid> </Window> 63

64 Menus and Toolbars A menu is logically nothing more than a TreeView control with a very special template TreeViewItem and MenuItem derive from the same base type: HeaderedItemsControl Both a menu and a toolbar provide effectively the same functionality: the ability to execute one or more commands The primary differences between the two are visual space and interaction model Menus and toolbars are typically paired with commands 64

65 Menus Menus consist of a series of MenuItem controls hosted within either Menu or ContextMenu In WPF, a menu is no longer relegated to the top of the window <Menu DockPanel.Dock="Bottom"> <MenuItem Header='_File'> <MenuItem Header='_New'/> <MenuItem Header='_Open' InputGestureText="Ctrl+O" /> <Separator/> <MenuItem Header='E_xit' Click="ExitMenuItem_Click"> <MenuItem.Icon> <Image Source="Images/Fiona_67x77.gif" Width="16" Height="16"></Image> </MenuItem.Icon> </MenuItem> </MenuItem> <MenuItem Header='_Edit'> <MenuItem Header='_Cut' /> <MenuItem Header='C_opy' /> <MenuItem Header='_Paste' /> </MenuItem> </Menu> 65

66 Toolbars Toolbars provide only one level of nesting There is a special host type for toolbars - ToolBarTray Each toolbar has a set of items and a header The content model allows to add anything as an item in the toolbar 66 <DockPanel> <ToolBarTray DockPanel.Dock='Top'> <ToolBar> <Button>Prev</Button> <Button>Next</Button> </ToolBar> <ToolBar> <TextBox Name="AddressTextBox" Width='200' Text=" /> <Button Width='23' Click="GoButton_Click">Go</Button> </ToolBar> </ToolBarTray> <WebBrowser Name="ContentWebBrowser"></WebBrowser> </DockPanel>

67 Containers TabControl provides the traditional tab-style UI It derives from Selector (and therefore ItemsControl) Expander offers the Windows XP-style expansion functionality known from the file explorer GroupBox provides a simple visual containment for separating parts of the UI TabItem, Expander, and GroupBox derive from HeaderedContentControl The HeaderedContentControl can contain a single header and single content model It can hold multiple items because a single layout container, like StackPanel or Grid, can be the root of that content 67

68 Containers Example 68 <TabControl> <TabItem Header='Tab 1'> <StackPanel> <Expander Header='Expander 1' IsExpanded='True'> <GroupBox Header='GroupBox 1'> <StackPanel Orientation="Horizontal"> <Label>Something 1</Label> <Image Source="Images/Fiona_67x77.gif"></Image> </StackPanel> </GroupBox> </Expander> <Expander Header='Expander 2'> <StackPanel> <GroupBox Header='GroupBox 2'> <Label>Something 2</Label> </GroupBox> <GroupBox Header="GroupBox 3"> <Label>Something 3</Label> </GroupBox> </StackPanel> </Expander> </StackPanel> </TabItem> <TabItem Header='Tab 2' /> </TabControl>

69 Range Controls Slider ScrollBar ProgressBar <UniformGrid Columns="2"> <Label Name="SliderLabel">0</Label> <Slider Name="MySlider" ValueChanged="MySlider_ValueChanged" TickPlacement="TopLeft" /> <Label Name="ScrollBarLabel">0</Label> <ScrollBar Name="MyScrollBar" ValueChanged="MyScrollBar_ValueChanged" Orientation="Horizontal" /> <Button Name="ProgressButton" Click="ProgressButton_Click"> Move progress </Button> <ProgressBar Name="MyProgressBar"/> </UniformGrid> private void MySlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e) { SliderLabel.Content = MySlider.Value; } private void MyScrollBar_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e) { ScrollBarLabel.Content = MyScrollBar.Value; } private void ProgressButton_Click(object sender, RoutedEventArgs e) { MyProgressBar.Value += MyProgressBar.SmallChange * 10; } 69

70 Editors PasswordBox provides the all-too-familiar function of a text box, except that it replaces what the user types with a series of dots or asterisks The password is secured, there is no way to disclose it by browsing the text tree TextBox supports only plain text RichTextBox enables to display or edit flow content including paragraphs, images, tables, and more RichTextBox hosts a FlowDocument object which in turn contains the editable content InkCanvas is an element that can be used to receive and display ink input 70

71 Editors Text Data There are two main concepts: block elements and inline elements Block elements occupy a rectangle of space; they start on a new line and are contiguous examples of block elements are Paragraph or Table Inline elements can span lines examples of inline elements are Span, Run, and Bold 71

72 Documents Examples 72

73 InkCanvas Example 73 <Canvas> <Canvas.Resources> <!--Define an array containing the InkEditingMode Values.--> <x:array x:key="myeditingmodes" x:type="{x:type InkCanvasEditingMode}"> <x:static Member="InkCanvasEditingMode.Ink"/> <x:static Member="InkCanvasEditingMode.Select"/> <x:static Member="InkCanvasEditingMode.EraseByPoint"/> <x:static Member="InkCanvasEditingMode.EraseByStroke"/> </x:array> </Canvas.Resources> <StackPanel> <ComboBox Name="cmbEditingMode" ItemsSource="{StaticResource MyEditingModes}" /> <InkCanvas EditingMode="{Binding ElementName=cmbEditingMode, Path=SelectedItem}"> </InkCanvas> </StackPanel> </Canvas>

74 Document Viewers RichTextBox editable scrolling view FlowDocumentScrollViewer continuous scrolling view FlowDocumentPageViewer paginated view, one page at a time FlowDocumentReader single-page view, multiple-page view, or scrolling view The optimal control for the user, where he can choose an appropriate view 74

75 FlowDocumentScrollViewer 75 FlowDocumentReader FlowDocumentPageViewer

76 ToolTip Usually, tool tip functionality is accessed using the ToolTip property on elements To adjust more tool tip properties ToolTipService can be used A custom template for the ToolTip control can be applied <Window x:class="wpfapplication1.ctrl_tooltip" xmlns=" xmlns:x=" Title="Ctrl_ToolTip" Height="100" Width="300"> <Window.Resources> <Style TargetType="{x:Type ToolTip}"> [...] </Style> </Window.Resources> <StackPanel> <Button ToolTip="The 1st button">button 1</Button> <Button ToolTip="The 2nd button">button 2</Button> <Button ToolTip="The 3rd button">button 3</Button> </StackPanel> </Window> 76

77 Thumb Thumb provides a region that can be moved It provides the ability to get events when a user drags this region (the thumb) around 77 <Canvas> <Thumb Canvas.Top = '5' Canvas.Left = '5' Width = '25' Height = '25' Name='MyThumb' DragStarted='ThumbStart' DragDelta='ThumbMoved' /> </Canvas> void ThumbMoved(object sender, DragDeltaEventArgs e) { Canvas.SetLeft(MyThumb, Canvas.GetLeft(MyThumb) + e.horizontalchange); Canvas.SetTop(MyThumb, Canvas.GetTop(MyThumb) + e.verticalchange); }

78 Border Border is a rectangle that can contain a child Most render elements (Rectangle, Ellipse, etc.) don t support children, so the Border can be used as their parent 78 <Canvas> <Border Canvas.Left='15' Canvas.Top='15' BorderThickness='3' CornerRadius='0' BorderBrush='Black' Padding='5'> <TextBlock>Hello 1</TextBlock> </Border> <Border Canvas.Left='85' Canvas.Top='15' BorderThickness='3' CornerRadius='3' BorderBrush='Black' Padding='5'> <TextBlock>Hello 2</TextBlock> </Border> <Border Canvas.Left='15' Canvas.Top='50' BorderThickness='10,1,10,1' CornerRadius='10' BorderBrush='Black' Padding='5'> <TextBlock>Hello 3</TextBlock> </Border> <Border Canvas.Left='85' Canvas.Top='50' BorderThickness='4,1,4,1' CornerRadius='0,15,0,15' BorderBrush='Black' Padding='5'> <TextBlock>Hello 4</TextBlock> </Border> </Canvas>

79 Popup The Popup control provides a way to display content in a separate window that floats over the current application window relative to a designated element or screen coordinate The following controls implement the Popup control for specific uses: ToolTip, ContextMenu, ComboBox, Expander <Button HorizontalAlignment="Left" Click="DisplayPopup" Width="150" Margin="20,10,0,0"> <StackPanel> <TextBlock>Display Your Popup Text</TextBlock> <Popup Name="myPopup"> <TextBlock Name="myPopupText" Background="LightBlue" Popup Text </TextBlock> </Popup> </StackPanel> </Button> private void DisplayPopup(object sender, RoutedEventArgs e) { mypopup.isopen =!mypopup.isopen; } Foreground="Blue"> 79

80 ScrollViewer The ScrollViewer control provides a convenient way to enable scrolling of content It encapsulates horizontal and vertical ScrollBar elements and a content container A ScrollViewer can only have one child, typically a Panel element that can host a Children collection of UIElements <Window x:class="wpfapplication1.ctrl_scrollviewer" xmlns=" xmlns:x=" Title="Ctrl_ScrollViewer" Height="300" Width="300"> <Window.Resources> [...] </Window.Resources> <ScrollViewer HorizontalScrollBarVisibility="Visible"> <DockPanel> <Button Width="400" Height="50">My button</button> <Button>My second button</button> </DockPanel> </ScrollViewer> </Window> 80

81 Viewbox Viewbox takes a single child and stretches it to fit by applying rendering transforms (stretching the content) <StackPanel Orientation="Vertical"> <StackPanel Margin="0,0,0,10" HorizontalAlignment="Center" Orientation="Horizontal" DockPanel.Dock="Top"> <Button Name="btn1" Click="stretchNone">Stretch="None"</Button> <Button Name="btn2" Click="stretchFill">Stretch="Fill"</Button> <Button Name="btn3" Click="stretchUni">Stretch="Uniform"</Button> <Button Name="btn4" Click="stretchUniFill">Stretch="UniformToFill"</Button> </StackPanel> <StackPanel Margin="0,0,0,10" HorizontalAlignment="Center" Orientation="Horizontal" DockPanel.Dock="Top"> <Button Name="btn5" Click="sdUpOnly">StretchDirection="UpOnly"</Button> <Button Name="btn6" Click="sdDownOnly">StretchDirection="DownOnly"</Button> <Button Name="btn7" Click="sdBoth">StretchDirection="Both"</Button> </StackPanel> <TextBlock DockPanel.Dock="Top" Name="txt1" /> <TextBlock DockPanel.Dock="Top" Name="txt2" /> <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center"> <Viewbox MaxWidth="500" MaxHeight="500" Name="vb1"> <Image Source="Images/Fiona_67x77.gif"/> </Viewbox> </StackPanel> </StackPanel> public void stretchnone(object sender, RoutedEventArgs e) { vb1.stretch = System.Windows.Media.Stretch.None; txt1.text = "Stretch is now set to None."; } 81

82 82 Layout

83 FrameworkElement FrameworkElement is the connecting point between WPF framework-level element classes and the WPF core-level set of UIElement presentation services FrameworkElement extends UIElement and adds the following capabilities: Layout system definition The logical tree Object lifetime events Support for data binding and dynamic resource references Styles More animation support 83

84 FrameworkElement Properties MinWidth, MaxWidth, MinHeight, MaxHeight Width, Height usually not set directly, to allow to resize automatically ActualHeight, ActualWidth report the final size of the element Margin - lets a child put a buffer of space around itself inside of the slot, but outside of the content of the control Negative values can also be used HorizontalAlignment, VerticalAlignment - determine how the child occupies the remaining space in the slot 84

85 Clipping Clipping is not the default WPF uses a composition engine that employs the painter s algorithm (painting from back to front) Clipping is expensive for each pixel there is a need to check if it should be visible 85 <UniformGrid Columns="1"> <StackPanel Orientation='Vertical' Background="AntiqueWhite"> <Button HorizontalAlignment='Center'>Center</Button> <Button HorizontalAlignment='Left'>Left</Button> <Button HorizontalAlignment='Right'>Right</Button> <Button HorizontalAlignment='Stretch'>Stretch</Button> </StackPanel> <StackPanel Orientation='Horizontal' Background="Chocolate"> <Button VerticalAlignment='Center'>Center</Button> <Button VerticalAlignment='Top'>Top</Button> <Button VerticalAlignment='Bottom' Margin="-20,0,0,0">Bottom</Button> <Button VerticalAlignment='Stretch' Margin="0,-20,0,-20">Stretch</Button> </StackPanel> </UniformGrid>

86 Transforms To adjust the final position of a control, two properties are available for making an arbitrary transformation: 86 RenderTransform is applied immediately before rendering7 (therefore affecting only rendering) LayoutTransform is applied before layout <TabControl> <TabItem Header="LayoutTransform"> <StackPanel Orientation="Horizontal"> <Button Width="100">15 <Button.LayoutTransform> <RotateTransform Angle="15"/> </Button.LayoutTransform> </Button> <Button Width="100">45 <Button.LayoutTransform> <RotateTransform Angle="45"/> </Button.LayoutTransform> </Button> </StackPanel> </TabItem> <!-- Analogously, but using the RenderTransform --> </TabControl>

87 Z-Index By default, all controls have a z-index of 0 87 <StackPanel> <Label>Default</Label> <WrapPanel> <Button Margin='-5'>Button One [0]</Button> <Button Margin='-5'>Button Two [0]</Button> <Button Margin='-5'>Button Three [0]</Button> <Button Margin='-5'>Button Four [0]</Button> </WrapPanel> <Rectangle Height="50"/> <Label>Modified ZIndex</Label> <WrapPanel> <Button Panel.ZIndex='2' Margin='-5'>Button One [2]</Button> <Button Margin='-5'>Button Two [0]</Button> <Button Panel.ZIndex='1' Margin='-5'>Button Three [1]</Button> <Button Margin='-5'>Button Four [0]</Button> </WrapPanel> </StackPanel>

88 Canvas Canvas is the simplest layout included in WPF It offers four properties: Top, Left, Right, and Bottom Only two properties can be used: one horizontal coordinate and one vertical coordinate It lets position its child elements at any offset from one corner of the panel <Canvas Width='200' Height='100' Background="AntiqueWhite" > <Button Canvas.Right='10' Canvas.Top='10'> Top, Right </Button> <Button Canvas.Left='10' Canvas.Top='10'> Top, Left </Button> <Button Canvas.Right='10' Canvas.Bottom='10'> Bottom, Right </Button> <Button Canvas.Left='10' Canvas.Bottom='10'> Bottom, Left </Button> <Button Canvas.Left='30' Canvas.Bottom='30' Canvas.Right='30' Canvas.Top='30'> All Four </Button> </Canvas> 88

89 StackPanel StackPanel stacks its child elements in a column (by default) or in a row (when the Orientation property is set to Horizontal) The slot for each child in StackPanel is given the entire width or height of the control (depending on its orientation) <Border BorderBrush='Black' BorderThickness='2' HorizontalAlignment='Center' VerticalAlignment='Center'> <StackPanel Orientation='Vertical'> <StackPanel Margin='10' Background='Green' Orientation='Horizontal'> <Button Margin='4'>One</Button> <Button Margin='4'>Two</Button> <Button Margin='4'>Three</Button> </StackPanel> <StackPanel Margin='5' Background='Blue' Orientation='Vertical'> <Button Margin='4'>One</Button> <Button Margin='4'>Two</Button> <Button Margin='4'>Three</Button> </StackPanel> </StackPanel> </Border> 89

90 DockPanel DockPanel allows mixing of stacking from different edges within the same layout container The LastChildFill property allows the last child to consume all the remaining space The Dock property allows to specify the edge to which a control is docked <DockPanel> <Button DockPanel.Dock='Top'>Menu Area</Button> <Button DockPanel.Dock='Top'>Toolbar Area</Button> <Button DockPanel.Dock='Left'>Folders</Button> <Button>Content</Button> </DockPanel> 90 <DockPanel> <Button DockPanel.Dock='Top'>Menu Area</Button> <Button DockPanel.Dock='Left'>Folders</Button> <Button DockPanel.Dock='Top'>Toolbar Area</Button> <Button>Content</Button> </DockPanel>

91 WrapPanel WrapPanel is a stack panel with wrapping support It uses the available space and fits elements to it; when it runs out of room, it wraps to the next line By default, WrapPanel simply sizes all the children to fit their content The width and height of the children by using the ItemWidth and ItemHeight properties 91 <StackPanel> <WrapPanel> <Button>1</Button> <Button>2nd</Button> <Button>3rd Button</Button> </WrapPanel> <Rectangle Height="50"/> <WrapPanel ItemWidth="75"> [...] </WrapPanel> <Rectangle Height="50"/> <WrapPanel ItemWidth="120"> [...] </WrapPanel> </StackPanel>

92 UniformGrid UniformGrid provides a very basic grid layout: each cell is the same size, and the locations of the items are determined simply by their order in the children collection The number of columns and optionally the number of rows can be set using the Columns and Rows properties resp. 92 <StackPanel> <UniformGrid Columns="2"> <Button>1</Button> <Button>2</Button> <Button>3</Button> <Button>4</Button> <Button>5</Button> </UniformGrid> <Rectangle Height="25"/> <UniformGrid Columns="2" Rows="2"> [...] </UniformGrid> <Rectangle Height="25" Opacity="0.5" Fill="Cyan" /> <UniformGrid Rows="2"> [...] </UniformGrid> </StackPanel>

93 Grid Grid is the most power, flexible, and complex of the UI layouts The simplest use of Grid is to set the RowDefinitions and ColumnDefinitions properties, add some children, and use the Grid.Row and Grid.Column attached properties to specify which child goes in which slot <Grid> <Grid.RowDefinitions> <RowDefinition /> <RowDefinition /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition /> <ColumnDefinition /> </Grid.ColumnDefinitions> <Button Grid.Row='0' Grid.Column='0' >[0,0]</Button> <Button Grid.Row='1' Grid.Column='1' >[1,1]</Button> <Button Grid.Row='0' Grid.Column='1' >[0,1]</Button> <Button Grid.Row='1' Grid.Column='0' >[1,0]</Button> </Grid> 93

94 Grid Percentage Sizing Example 94 <Grid> <Grid.RowDefinitions> <RowDefinition Height="1*"/> <RowDefinition Height="3*" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="40*"/> <ColumnDefinition Width="50*"/> </Grid.ColumnDefinitions> <Button Grid.Row='0' Grid.Column='0' >[0,0]</Button> <Button Grid.Row='1' Grid.Column='1' >[1,1]</Button> <Button Grid.Row='0' Grid.Column='1' >[0,1]</Button> <Button Grid.Row='1' Grid.Column='0' >[1,0]</Button> </Grid>

95 Grid Shared Size Example 95 <Grid> [...] <Grid.ColumnDefinitions> <ColumnDefinition/> <ColumnDefinition/> </Grid.ColumnDefinitions> [...] </Grid> [...] <Grid> [...] <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="Auto"/> </Grid.ColumnDefinitions> [...] </Grid> [...] <Grid Grid.IsSharedSizeScope="True"> [...] <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" SharedSizeGroup="ssg01"/> <ColumnDefinition Width="Auto" SharedSizeGroup="ssg01"/> </Grid.ColumnDefinitions> [...] </Grid>

96 GridSplitter GridSplitter is a normal control (supporting templates, etc.) that allows the user to edit the layout of a row or column at runtime <Grid> <Grid.RowDefinitions> <RowDefinition Height="50*" /> <RowDefinition Height="Auto" /> <RowDefinition Height="50*" /> </Grid.RowDefinitions> <StackPanel Grid.Row="0" Grid.Column="1" Background="Tan"/> <GridSplitter Grid.Row="1" HorizontalAlignment="Stretch" VerticalAlignment="Center" Background="Black" ShowsPreview="True" Height="5" /> <StackPanel Grid.Row="2" Grid.Column="0" Background="Brown"/> </Grid> <Grid> <Grid.RowDefinitions> <RowDefinition Height="50*" /> <RowDefinition Height="50*" /> </Grid.RowDefinitions> <StackPanel Grid.Row="0" Grid.Column="1" Background="Tan"/> <GridSplitter Grid.Row="0" HorizontalAlignment="Stretch" VerticalAlignment="Bottom" Background="Black" ShowsPreview="True" Height="5" ResizeBehavior="CurrentAndNext" /> <StackPanel Grid.Row="1" Grid.Column="0" Background="Brown"/> </Grid> 96

97 97 Graphics and Multimedia

98 Overview Benefits of WPF graphics: Resolution and device-independent Improved precision Advanced graphics and animation support Hardware acceleration Available graphics elements: 2-D shapes 2-D geometries 2-D effects 3-D rendering Animation Media: images, video, and audio 98

99 Graphics Rendering Visual the basic abstraction from which every FrameworkElement object derives It is a core WPF object, whose primary role is to provide rendering support It provides support for: output display, transformations, clipping, hit testing, and bounding box calculations It does not provide support for: event handling, layout, styles, data binding, and globalization A Visual object stores its render data as a vector graphics instruction list; there are 4 types of render data: vector graphics image glyph video 99

100 Graphics Rendering cont. DrawingVisual used to render shapes, images, or text It can be used to create a custom visual object Viewport3DVisual a bridge between 2D Visual and Visual3D objects It requires to define a Camera value and a Viewport value ContainerVisual a container for a collection of Visual objects Drawing an abstract class describing a 2-D drawing A base class for: DrawingGroup, GeometryDrawing, GlyphRunDrawing, ImageDrawing, VideoDrawing 100

101 Graphics Rendering cont. DrawingGroup describes operations that are applied to its contents in the following order: 1. OpacityMask 2. Opacity 3. BitmapEffect 4. ClipGeometry 5. GuidelineSet 6. Transform DrawingContext populates a Visual with visual content acquired from certain methods, e.g. DrawingGroup.Open and DrawingVisual.RenderOpen 101

102 Visual Rendering Behaviour Application objects that have a visual appearance define a set of serialized drawing data The system is responsible for responding to all repaint requests for rendering the application objects WPF can efficiently optimize what needs to be redrawn in the application WPF uses vector graphics as its rendering data format WPF supports automatic scaling by using the device independent pixel as its primary unit of measurement Logical pixel equates to 1/96 of an inch (which is consistent with standard resolution of Windows) Graphics and text scale properly without any extra work from the application developer 102

103 Transformations A Transform is a 3x3 Matrix: M11 M M21 M OffsetX OffsetY 0.1 RotateTransform, ScaleTransform, SkewTransform, TranslateTransform The Transform class inherits from the Animatable class, so it can be animated To apply multiple transforms to an UI element, use a TransformGroup <Button Content="A Button" RenderTransformOrigin="0.5,0.5"> <Button.RenderTransform> <RotateTransform x:name="animatedrotatetransform" Angle="0" /> </Button.RenderTransform> <Button.Triggers> <EventTrigger RoutedEvent="Button.Click"> <BeginStoryboard> <Storyboard> <DoubleAnimation Storyboard.TargetName= "AnimatedRotateTransform" Storyboard.TargetProperty= "Angle" To="360" Duration="0:0:1" FillBehavior="Stop" /> </Storyboard> </BeginStoryboard> </EventTrigger> </Button.Triggers> </Button> 103

104 Bitmap Effects A bitmap effect takes a BitmapSource as an input and produces a new BitmapSource after applying the effect As a special case, in WPF, effects can be set as properties on live Visual objects In this case, at the time of rendering, a Visual is automatically converted to its BitmapSource, so the output replaces the Visual object's default rendering Available effects: BlurBitmapEffect OuterGlowBitmapEffect DropShadowBitmapEffect BevelBitmapEffect EmbossBitmapEffect Custom effects can be created 104

105 Bitmap Effects Example 105 <TabControl> <TabItem Header="None"> <Canvas> <Button>Button</Button> <TextBlock Canvas.Left="50"> Text in a textblock</textblock> <Image Canvas.Top="35" Source="/Images/Fiona_67x77.gif"/> </Canvas> </TabItem> <TabItem Header="Blur"> <Canvas> <Canvas.BitmapEffect> <BlurBitmapEffect/> </Canvas.BitmapEffect> <Button>Button</Button> <TextBlock Canvas.Left="50"> Text in a textblock</textblock> <Image Canvas.Top="35" Source="/Images/Fiona_67x77.gif"/> </Canvas> </TabItem> [...] </TabControl>

106 Brushes Everything visible on a screen is visible because it was painted by a brush Available brushes: SolidColorBrush LinearGradientBrush RadialGradientBrush ImageBrush (uses a ImageSource) DrawingBrush (uses a Drawing which can contain shapes, images, text, and media) VisualBrush (uses a Visual object, e.g. Button) Common brush features: Opacity Transform, RelativeTransform can be animated can be frozen (i.e. cannot be modified) 106

107 Gradient Brushes Examples 107 <Rectangle Width="200" Height="100"> <Rectangle.Fill> <LinearGradientBrush StartPoint="0,0" EndPoint="1,1"> <GradientStop Color="Yellow" Offset="0.0" /> <GradientStop Color="Red" Offset="0.25" /> <GradientStop Color="Blue" Offset="0.75" /> <GradientStop Color="LimeGreen" Offset="1.0" /> </LinearGradientBrush> </Rectangle.Fill> </Rectangle> <Rectangle Width="200" Height="100"> <Rectangle.Fill> <RadialGradientBrush GradientOrigin="0.5,0.5" Center="0.5,0.5" RadiusX="0.5" RadiusY="0.5"> <GradientStop Color="Yellow" Offset="0" /> <GradientStop Color="Red" Offset="0.25" /> <GradientStop Color="Blue" Offset="0.75" /> <GradientStop Color="LimeGreen" Offset="1" /> </RadialGradientBrush> </Rectangle.Fill> </Rectangle>

108 <StackPanel Canvas.Top="300" Canvas.Left="50"> <Border Name="ReflectedVisual">[...]</Border> VisualBrush Example <Rectangle Height="1" Fill="Gray" HorizontalAlignment="Stretch" /> <Rectangle Height="{Binding Path=ActualHeight, ElementName=ReflectedVisual}" Width="{Binding Path=ActualWidth, ElementName=ReflectedVisual}"> <Rectangle.Fill> <VisualBrush Opacity="0.75" Stretch="None" Visual="{Binding ElementName=ReflectedVisual}"> <VisualBrush.RelativeTransform> <TransformGroup> <ScaleTransform ScaleX="1" ScaleY="-1" /> <TranslateTransform Y="1" /> </TransformGroup> </VisualBrush.RelativeTransform> </VisualBrush> </Rectangle.Fill> <Rectangle.OpacityMask> <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1"> <GradientStop Color="#FF000000" Offset="0.0" /> <GradientStop Color="# " Offset="0.5" /> <GradientStop Color="# " Offset="0.9" /> </LinearGradientBrush> </Rectangle.OpacityMask> <Rectangle.BitmapEffect> <BlurBitmapEffect Radius="1.5" /> </Rectangle.BitmapEffect> </Rectangle> </StackPanel> 108

109 TileBrush Examples TileMode Stretch Viewport, ViewportUnits 109

110 Opacity Masks 110

111 Brush Transformation Algorithm used for processing and transforming a brush: 1. Process the brush s contents 2. Project the brush s output onto the 1 x 1 transformation rectangle 3. Apply the brush s RelativeTransform, if it has one 4. Project the transformed output onto the area to paint 5. Apply the brush s Transform, if it has one 111 The output of several brushes that have been rotated by 45 degrees using the RelativeTransform and Transform properties

112 Shapes The Shape class is a base for all available shape objects: Ellipse, Line, Path, Polygon, Polyline, and Rectangle Common properties of shape objects: Stroke how the shape's outline is painted StrokeThickness thickness of the shape's outline Fill how the interior of the shape is painted Transform Stretch (not available for an Ellipse) PointCollection mypointcollection = new PointCollection(); mypointcollection.add(new Point(0, 0)); mypointcollection.add(new Point(0, 1)); mypointcollection.add(new Point(1, 1)); 112 <Polygon Points="0,0 0,1 1,1" Fill="Blue" Width="100" Height="100" Stretch="Fill" Stroke="Black" StrokeThickness="2" /> Polygon mypolygon = new Polygon(); mypolygon.points = mypointcollection; mypolygon.fill = Brushes.Blue; mypolygon.width = 100; mypolygon.height = 100; mypolygon.stretch = Stretch.Fill; mypolygon.stroke = Brushes.Black; mypolygon.strokethickness = 2;

113 Geometry The Geometry class and the classes which derive from it enable to describe the geometry of a 2-D shape Geometry objects are more versatile than Shape objects A Shape object is used to render 2-D graphics A Geometry object can be used to define the geometric region for 2-D graphics, define a region for clipping, or define a region for hit testing, for example The Path shape uses a Geometry to describe its contents It can be used to render a Geometry (by setting the Data, Fill, and Stroke properties) 113

114 Available Geometries Simple geometry types: LineGeometry, RectangleGeometry, EllipseGeometry A PathGeometry contains a collection of PathFigure objects. Each PathFigure object can contain segments: LineSegment, PolyLineSegment, ArcSegment, BezierSegment, PolyBezierSegment, QuadraticBezierSegment, PolyQuadraticBezierSegment A StreamGeometry defines a complex geometric shape that may contain curves, arcs, and lines The contents of a StreamGeometry do not support data binding, animation, or modification (unlike a PathGeometry) The CombinedGeometry object and the Combine method performs a boolean operation to combine the area defined by two geometries The GeometryGroup class creates an amalgamation of the Geometry objects it contains without combining their area 114

115 PathGeometry Example 115 <Image Source="/Images/Osiol_157x200.gif"> <Image.Clip> <!--<Path Stroke="Black" StrokeThickness="1" > <Path.Data>--> <PathGeometry> <PathGeometry.Figures> <PathFigure StartPoint="20,20"> <PathFigure.Segments> <LineSegment Point="50,50"/> <ArcSegment Point="80,100" Size="10,20" SweepDirection="Clockwise"/> <BezierSegment Point1="90,80" Point2="110,100" Point3="130,120"/> <PolyBezierSegment Points="140,200,160,0,150,150,190,200,180,180,100,150"/> <QuadraticBezierSegment Point1="80,200" Point2="20,20"/> </PathFigure.Segments> </PathFigure> </PathGeometry.Figures> </PathGeometry> <!--</Path.Data> </Path>--> </Image.Clip> </Image>

116 Path Markup Syntax <Path Stroke="Black" Fill="Gray" Data="M 10,100 C 10, , ,100 V 200 H 10 Z" /> 116 M move L line H horizontal line V vertical line C cubic Bezier curve Q quadratic Bezier curve S smooth Bezier curve A elliptical arc Z close path <Path Stroke="Black" Fill="Gray"> <Path.Data> <PathGeometry> <PathGeometry.Figures> <PathFigure StartPoint="10,100" IsClosed="True"> <PathFigure.Segments> <BezierSegment Point1="10,300" Point2="200,-200" Point3="200,100"/> <LineSegment Point="200,200"/> <LineSegment Point="10,200"/> </PathFigure.Segments> </PathFigure> </PathGeometry.Figures> </PathGeometry> </Path.Data> </Path>

117 Imaging WPF Imaging includes a codec for BMP, JPEG, PNG, TIFF, Windows Media Photo, GIF, and ICON image formats ICON is the only format without encoding support A BitmapSource represents a single, constant set of pixels at a certain size and resolution It can be an individual frame of a multiple frame image, or it can be the result of a transform performed on a BitmapSource A BitmapFrame is used to store the actual bitmap data of an image format Access to image metadata is provided through the Metadata property of a BitmapSource object 117

118 3-D Graphics 3-D graphics content in WPF is encapsulated in an element, Viewport3D, that can participate in the two-dimensional element structure Viewport3D is a surface on which a 3-D scene is projected It can be used, as other container elements, with other 2-D drawing objects in the same scene graph 2-D and 3-D objects cannot be interpenetrated within a Viewport3D Coordinate systems for 2-D and 3-D graphics differ: 118 Available 3-D transformations (inherited from the abstract Transform3D class): TranslateTransform3D, ScaleTransform3D, RotateTransform3D

119 3-D Graphics cont. Camera allows to specify the onlooker's point of view for a 3-D scene ProjectionCamera allows to specify different projections and their properties to change how the onlooker sees 3-D models PerspectiveCamera specifies a projection that foreshortens the scene Model3D is the abstract base class that represents a generic 3-D object. The objects that make up the scene graph derive from this class GeometryModel3D creates a 3-D model comprised of a MeshGeometry3D and a Material Available lights: AmbientLight, DirectionalLight, PointLight, SpotLight 119

120 Windows <!-- Viewport3D Presentationis Foundation the rendering surface. --> <Viewport3D Name="myViewport" > 3-D <!-- Add Graphics a camera. --> Example <Viewport3D.Camera> <PerspectiveCamera FarPlaneDistance="20" LookDirection="0,0,1" FieldOfView="45" UpDirection="0,1,0" NearPlaneDistance="1" Position="0,0,-3" /> </Viewport3D.Camera> <!-- Add models. --> <Viewport3D.Children> <ModelVisual3D> <ModelVisual3D.Content> <Model3DGroup > <Model3DGroup.Children> <!-- Lights, MeshGeometry3D and DiffuseMaterial --> <DirectionalLight Color="#FFFFFFFF" Direction="3,-4,5" /> <!-- Define a red cone. --> <GeometryModel3D> <GeometryModel3D.Geometry> <MeshGeometry3D [...] /> </GeometryModel3D.Geometry> <GeometryModel3D.Material> <DiffuseMaterial> <DiffuseMaterial.Brush> <SolidColorBrush Color="Red" Opacity="1.0"/> </DiffuseMaterial.Brush> </DiffuseMaterial> </GeometryModel3D.Material> [...] 120

121 Animation WPF includes an efficient timing system that is exposed through managed code and XAML and that is deeply integrated into the WPF framework WPF animation makes it easy to animate controls and other graphical objects In WPF, object are animated by applying animation to their properties. A property can be animated if: It is a dependency property It belongs to a class that inherits from DependencyObject and implements IAnimatable There is a compatible animation type available Animations can be used almost anywhere, which includes in styles and control templates Animations do not have to be visual 121

122 Animation Types <Type>Animation (e.g. DoubleAnimation or ColorAnimation) It animate between a starting (From) and destination value (To), or by adding an offset value (By) to its starting value <Type>AnimationUsingKeyFrames Any number of target values and their interpolation method can be specified <Type>AnimationUsingPath Allows to use a geometric path in order to produce animated values <Type>AnimationBase Abstract class which can be used to create custom animations 122

123 Timeline All the animation types inherit from the Timeline class A Timeline defines a segment of time and allows to specify the following properties: Duration (the default is 1 second) AutoReverse whether a timeline playes backward after it reaches the end of its duration RepeatBehavior specifies how many times a timeline plays (the default is 1.0) FillBehavior specifies what should be done with the value of the animated property when the animation stops The real work of keeping time control is done by the timeline's Clock A Clock provides information essential to the animation: CurrentTime, CurrentProgress, and CurrentState 123

124 Animation Example Fade In and Out 1. Create a DoubleAnimation (it creates a transition between two double values) 2. Create a Storyboard (use the TargetName property to specify the object to animate and TargetProperty to specify the property to animate) 3. Associate the Storyboard with a trigger 124 <Rectangle Name="MyRectangle" Width="100" Height="100" Fill="Blue"> <Rectangle.Triggers> <EventTrigger RoutedEvent="Rectangle.Loaded"> <BeginStoryboard> <Storyboard> <DoubleAnimation Storyboard.TargetName="MyRectangle" Storyboard.TargetProperty="Opacity" From="1.0" To="0.0" Duration="0:0:5" AutoReverse="True" RepeatBehavior="Forever" /> </Storyboard> </BeginStoryboard> </EventTrigger> </Rectangle.Triggers> </Rectangle>

125 Key-Frame Animation Available interpolation methods Linear interpolation the animation progresses at a constant rate of the segment duration Discrete interpolation the animation function jumps from one value to the next without interpolation Splined interpolation the animation is based on a Bezier curve which describes the rate of change for that spline key frame Two points of the curve are constant (0.0, 0.0), (1.0, 1.0), the other two can be set using the KeySpline property Key frames with different interpolation types can be used in a single key frame animation The KeyTime property of the animation key frame's specifies when that key frame ends It is possible to specify the KeyTime property's value in percentage The special value "Paced" can be used when a constant rate is desired 125

126 Key-Frame Animation Examples 126 <Storyboard> <DoubleAnimationUsingKeyFrames Storyboard.TargetName="MyAnimatedTranslateTransform" Storyboard.TargetProperty="X" Duration="0:0:10"> <LinearDoubleKeyFrame Value="0" KeyTime="0:0:0" /> <LinearDoubleKeyFrame Value="350" KeyTime="0:0:2" /> <LinearDoubleKeyFrame Value="50" KeyTime="0:0:7" /> <LinearDoubleKeyFrame Value="200" KeyTime="0:0:8" /> </DoubleAnimationUsingKeyFrames> </Storyboard> <Storyboard> <DoubleAnimationUsingKeyFrames Storyboard.TargetName="ComboAnimatedTranslateTransform" Storyboard.TargetProperty="X" Duration="0:0:15" RepeatBehavior="Forever"> <DiscreteDoubleKeyFrame Value="500" KeyTime="0:0:7" /> <LinearDoubleKeyFrame Value="200" KeyTime="0:0:10" /> <SplineDoubleKeyFrame Value="350" KeyTime="0:0:15" KeySpline="0.25, ,1" /> </DoubleAnimationUsingKeyFrames> </Storyboard>

127 Path Animation A path animation uses a PathGeometry as its input As the path animation progresses, it reads the x, y, and angle information from the path and uses that information to generate its output There are 3 typed of path animations: A MatrixAnimationUsingPath generates Matrix values from its PathGeometry one way to move an object along a path is to use a MatrixTransform and a MatrixAnimationUsingPath to transform an object along a complex path the DoesRotateWithTangent property can be used to force the object to rotate along the tangent of the path A PointAnimationUsingPath generates Point values from the x- and y-coordinates of its PathGeometry A DoubleAnimationUsingPath generates Double values from its PathGeometry 127

128 Path Animation Example 128 <Button MinWidth="100" Content="A Button"> <Button.RenderTransform> <MatrixTransform x:name="buttonmatrixtransform"/> </Button.RenderTransform> <Button.Triggers> <EventTrigger RoutedEvent="Button.Loaded"> <BeginStoryboard> <Storyboard> <MatrixAnimationUsingPath Storyboard.TargetName="ButtonMatrixTransform" Storyboard.TargetProperty="Matrix" DoesRotateWithTangent="True" Duration="0:0:5" RepeatBehavior="Forever" > <MatrixAnimationUsingPath.PathGeometry> <PathGeometry Figures="M 10,100 C 35,0 135,0 160, , , ,100" PresentationOptions:Freeze="True" /> </MatrixAnimationUsingPath.PathGeometry> </MatrixAnimationUsingPath> </Storyboard> </BeginStoryboard> </EventTrigger> </Button.Triggers> </Button>

129 Property Animation Techniques There are 4 ways to animate a property of an object: Storyboard animation allows to define and apply animations in XAML, interactively control animations after they start, create a complex tree of animations, or animate in a Style, ControlTemplate or DataTemplate Local animation provide a convenient way to animate a dependency property of any Animatable object Clock animation allows to create complex timing trees or interactively control animations after they start Per-frame animation useful when there is a need to completely bypass the WPF animation system, e.g. physics animations 129

130 Storyboard A Storyboard is a type of container timeline that provides targeting information for the timelines it contains It can be used to animate dependency properties of animatable classes The animated object must belong to the NameScope of a FrameworkElement or a FrameworkContentElement To apply animations to their targets, begin the Storyboard using a trigger action or a method In XAML, use a BeginStoryboard object with an EventTrigger, Trigger, or DataTrigger In code, use the Begin method The Storyboard can be controlled using code or XAML Available operations: pause, resume, seek, skiptofill, stop, remove 130

131 Timing Events There are 5 timing events provided by the Timeline and Clock classes: Completed, CurrentGlobalSpeedInvalidated, CurrentStateInvalidated, CurrentTimeInvalidated, RemoveRequested 131 mystoryboard.stop(myrectangle); // This statement might execute before the storyboard has stopped. myrectangle.fill = Brushes.Blue; // Register for the CurrentStateInvalidated timing event. mystoryboard.currentstateinvalidated += new EventHandler(myStoryboard_CurrentStateInvalidated); // Change the rectangle's color after the storyboard stops. void mystoryboard_currentstateinvalidated(object sender, EventArgs e) { Clock mystoryboardclock = (Clock)sender; if (mystoryboardclock.currentstate == ClockState.Stopped) { myrectangle.fill = Brushes.Blue; } }

132 Freezable A Freezable is a special type of object that has two states: unfrozen and frozen When frozen, a Freezable can no longer be modified Freezing a Freezable can improve its performance, because it no longer needs to spend resources on change notifications A frozen Freezable can also be shared across threads, while an unfrozen Freezable cannot To freeze the object, call the Freeze method To avoid throwing an InvalidOperationException, check the value of the Freezable object's CanFreeze property before calling Freeze Use the IsFrozen property can be used to check if the object is frozen 132

133 Multimedia There are 2 classes that can be used to present audio, video, and video with audio content; both rely on a minimum of the Microsoft Windows Media Player 10 OCX for media playback MediaElement is a UIElement that can be consumed as the content of many controls it is usable in XAML and code MediaPlayer is designed for Drawing objects media loaded using a MediaPlayer can only be presented using a VideoDrawing or by directly interacting with a DrawingContext it cannot be used in XAML Two media modes are supported: Independent mode media content drives media playback Clock mode a MediaTimeline drives media playback 133

134 MediaElement To play media in an application, just add a MediaElement control to the user interface and provide a Uri to the media The LoadedBehavior and UnloadedBehavior properties control the behaviour of the MediaElement when IsLoaded is true or false, respectively To display a MediaElement it must have content to render and it will have its ActualWidth and ActualHeight properties set to zero until content is loaded For video content, once the MediaOpened event has been raised the ActualWidth and ActualHeight will report the size of the loaded media Setting both the Width and Height properties will cause the media to stretch to fill the area provided for the MediaElement To preserve the media's original aspect ratio, either the Width or Height property should be set but not both 134

135 <StackPanel Name="MainPanel" Background="Black"> <MediaElement Name="myMediaElement" MediaOpened="Element_MediaOpened" /> <StackPanel HorizontalAlignment="Center" Example Width="260" Orientation="Horizontal"> <Button Name="PlayButton" Margin="30,10,10,10">Play</Button> <Button Name="PauseButton" Margin="10">Pause</Button> <Button Name="ResumeButton" Margin="10">Resume</Button> <Button Name="StopButton" Margin="10">Stop</Button> </StackPanel> <Slider Name="timelineSlider" Margin="5" HorizontalAlignment="Center" /> <StackPanel.Triggers> <EventTrigger RoutedEvent="Button.Click" SourceName="PlayButton"> <EventTrigger.Actions> <BeginStoryboard Name= "mybegin"> <Storyboard SlipBehavior="Slip"> <MediaTimeline Source="Movies\TestMovie.wmv" Storyboard.TargetName="myMediaElement" CurrentTimeInvalidated="MediaTimeChanged" /> </Storyboard> </BeginStoryboard> </EventTrigger.Actions> </EventTrigger> <EventTrigger RoutedEvent="Button.Click" SourceName="PauseButton"> <EventTrigger.Actions> <PauseStoryboard BeginStoryboardName="myBegin" /> </EventTrigger.Actions> </EventTrigger> [...] </StackPanel.Triggers> </StackPanel> 135

136 MediaPlayer 136 MediaTimeline timeline = new MediaTimeline( new Uri(@"Movies\TestMovie.wmv", UriKind.Relative)); timeline.repeatbehavior = RepeatBehavior.Forever; // Create the clock, which is shared with the MediaPlayer MediaClock clock = timeline.createclock(); MediaPlayer player = new MediaPlayer(); player.clock = clock; // Create the VideoDrawing VideoDrawing videodrawing = new VideoDrawing(); videodrawing.rect = new Rect(0, 0, 1, 1); videodrawing.player = player; // Assign the DrawingBrush DrawingBrush brush = new DrawingBrush(videoDrawing); brush.viewport = new Rect(0, 0, 0.5, 0.25); brush.tilemode = TileMode.Tile; // Start the timeline clock.controller.begin(); MainCanvas.Background = brush; <Canvas Name="MainCanvas" Background="Pink" />

137 137 Data

138 Resources Every framework-level element (FrameworkElement or FrameworkContentElement) has a Resources property This property contains the resources (as a ResourceDictionary) that a resource defines Resources can be defined on any element, however, usually the root element (Window or Page) is used In general, it is best to define resources in the lowest level of scoping Each resource in a resource dictionary must have a unique key In markup, the x:key attribute is used 138 Resources are a specialized form of data binding, optimized for a high number of bindings with low update frequency

139 <Window.Resources> <SolidColorBrush x:key="mybrush" Color="Gold"/> <Style TargetType="Border" x:key="pagebackground"> Resources <Setter Property="Background" Example Value="Blue"/> </Style> <Style TargetType="TextBlock" x:key="titletext"> <Setter Property="DockPanel.Dock" Value="Top"/> <Setter Property="FontSize" Value="18"/> <Setter Property="Foreground" Value="#4E87D4"/> <Setter Property="FontFamily" Value="Trebuchet MS"/> <Setter Property="Margin" Value="0,40,10,10"/> </Style> <Style TargetType="TextBlock" x:key="label"> <Setter Property="DockPanel.Dock" Value="Right"/> <Setter Property="FontSize" Value="8"/> <Setter Property="Foreground" Value="{StaticResource MyBrush}"/> <Setter Property="FontFamily" Value="Arial"/> </Style> </Window.Resources> <StackPanel> <Border Style="{StaticResource PageBackground}"> <DockPanel> <TextBlock Style="{StaticResource TitleText}">Title</TextBlock> <TextBlock Style="{StaticResource Label}">Label</TextBlock> <TextBlock DockPanel.Dock="Top" HorizontalAlignment="Left" FontSize="36" Foreground="{StaticResource MyBrush}" Text="Text" Margin="20" /> <Button DockPanel.Dock="Top" HorizontalAlignment="Left" Height="30" Background="{StaticResource MyBrush}" Margin="40">Button</Button> </DockPanel> </Border> Krzysztof </StackPanel> Mossakowski Windows Presentation Foundation 139

140 Resources cont. Resources can also be defined at Application level In such case, they are available for all windows, pages, etc. 140 <Application x:class="wpfapplication1.app" xmlns=" xmlns:x=" StartupUri="Data/Resources.xaml" Startup="Application_Startup" Exit="Application_Exit"> <Application.Resources> <SolidColorBrush x:key="mainbrush">black</solidcolorbrush> </Application.Resources> </Application> <Window [...]> <Ellipse DockPanel.Dock="Top" HorizontalAlignment="Left" Width="100" Height="100" Fill="{StaticResource MainBrush}" Margin="40" /> </Window>

141 Dynamic Resources Dynamic resources can be modified at runtime It can be used to cause updates across all the windows or pages in an application <Ellipse DockPanel.Dock="Top" HorizontalAlignment="Left" Width="100" Height="100" Margin="40" Fill="{DynamicResource MainBrush}" MouseDown="Ellipse_MouseDown" /> private void Ellipse_MouseDown(object sender, MouseButtonEventArgs e) { Application.Current.Resources["MainBrush"] = new SolidColorBrush(Colors.Blue); } To perform a dynamic resource binding in code, use the SetResourceReference method button1.setresourcereference(button.backgroundproperty,"mainbrush"); Using dynamic resource references does introduce some performance overhead 141

142 Data Binding Data binding is a relationship that tells WPF to extract some information from a source object and use it to set a property in a target object The target property is always a dependency property, and it s usually in a WPF element The source object can be just about anything, ranging from another WPF element to an ADO.NET data object or a data-only custom object 142

143 Element-To-Element Binding Example 143 <StackPanel> <StackPanel.Resources> <x:array x:key="availablecolors" x:type="{x:type Color}"> <x:static Member="Colors.Black"/> <x:static Member="Colors.Red"/> <x:static Member="Colors.Green"/> <x:static Member="Colors.Blue"/> </x:array> <CollectionViewSource Source="{Binding Source={x:Static Fonts.SystemFontFamilies}}" x:key="availablefontfamilies"/> </StackPanel.Resources> <ComboBox Name="fontFamilyComboBox" ItemsSource="{Binding Source={StaticResource AvailableFontFamilies}}" SelectedIndex="0" IsReadOnly="True"> <ComboBox.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding}" FontFamily="{Binding}"/> </DataTemplate> </ComboBox.ItemTemplate> </ComboBox>

144 <ComboBox Name="colorsComboBox" ItemsSource="{StaticResource AvailableColors}" Windows Presentation Foundation Element-To-Element SelectedIndex="2" IsReadOnly="True"> Binding Example <ComboBox.ItemTemplate> <DataTemplate> <Border x:name="selecteditemborder" MinHeight="16" MinWidth="100" > <Border.Background> <SolidColorBrush Color="{Binding}"/> </Border.Background> </Border> </DataTemplate> </ComboBox.ItemTemplate> </ComboBox> 144 <TextBox Name="textBox">Something</TextBox> <Slider Name="sizeSlider" TickFrequency="1" TickPlacement="TopLeft" Minimum="1" Maximum="96" Value="10"/> <TextBlock Text="{Binding ElementName=textBox, Path=Text}" FontSize="{Binding ElementName=sizeSlider, Path=Value}" FontFamily= "{Binding ElementName=fontFamilyComboBox, Path=SelectedItem}" > <TextBlock.Foreground> <SolidColorBrush Color= "{Binding ElementName=colorsComboBox, Path=SelectedItem}" /> </TextBlock.Foreground> </TextBlock> </StackPanel>

145 Binding Errors WPF doesn t raise exceptions to notify about data binding problems If the property does not exist, the data will simply fail to appear Fortunately, WPF does output trace information that details binding failures This information appears in Visual Studio s Output window when you re debugging the application System.Windows.Data Error: 22 : Cannot convert '#FF008000' from type 'Color' to type 'System.Windows.Media.Brush' for 'en-us' culture with default conversions; consider using Converter property of Binding. NotSupportedException: 'System.NotSupportedException: BrushConverter cannot convert from System.Windows.Media.Color. at System.ComponentModel.TypeConverter.GetConvertFromException(Object value) at System.ComponentModel.TypeConverter.ConvertFrom(ITypeDescriptorContext at System.Windows.Media.BrushConverter.ConvertFrom(ITypeDescriptorContext at MS.Internal.Data.DefaultValueConverter.ConvertHelper(Object o, Type 145 It is possible to change the appearance of the source element to indicate that an error has occurred

146 Creating Bindings with Code 146 Binding binding = new Binding(); binding.source = sizeslider; binding.path = new PropertyPath("Value"); previewtextblock.setbinding(fontsizeproperty, binding); Binding can be removed using one of two static method of the BindingOperations class: ClearBinding or ClearAllBindings These methods can remove also bindings defined in XAML It is preferred to define bindings in XAML

147 Binding Direction There are 5 available binding modes defined in the BindingMode enumeration: OneWay the target is updated according to the source's changes TwoWay the target is updated when the source changes, and the source is updated when the target changes OneTime the target is set initially and all later changes of the source are ignored OneWayToSource the source is updated according the target's changes Default it is either TwoWay (for user-settable properties, e.g. TextBox.Text) or OneWay (for everything else) 147

148 Binding to Objects That Aren't Elements Any public property of any object can be used as a source for binding It must be a public property private information or public fields cannot be used One of the following properties can be used for binding to objects that aren't elements: Source RelativeSource DataContext 148

149 Binding: Source The Source property points the object (and its public property) The simplest option is to point the Source to some static object that s readily available <TextBlock Text="{Binding Source={x:Static SystemFonts.IconFontFamily}}" /> 149 Another option is to bind to an object that was previously created as a resource <StackPanel.Resources> <FontFamily x:key="specialfont">trebuchet MS</FontFamily> </StackPanel.Resources> <TextBlock Text="{Binding Source={StaticResource SpecialFont}}" />

150 Binding: RelativeSource The RelativeSource property allows you to point to a source object based on its relation to the target object One option is to use the property-setting syntax instead of the Binding markup extension: <TextBlock> <TextBlock.Text> <Binding Path="Title"> <Binding.RelativeSource> <RelativeSource Mode="FindAncestor" AncestorType="{x:Type Window}" /> </Binding.RelativeSource> </Binding> </TextBlock.Text> </TextBlock> The more common way is to combine the binding into one string using the Binding and RelativeSource markup extensions: <TextBlock Text="{Binding Path=Title, RelativeSource= {RelativeSource FindAncestor, AncestorType={x:Type Window}}}"> </TextBlock> 150

151 Binding: RelativeSourceMode There are four options available for RelativeSources: Self the expression binds to another property in the same element FindAncestor - the expression binds to a parent element; the AncestorType property must be used, optionally also the AncestorLevel property can be used PreviousData the expression binds to the previous data item in a data-bound list TemplatedParent the expression binds to the element on which the template is applied; it works only if the binding is located inside a control template or data template 151

152 Binding: DataContext When the source information is missing from a binding expression, WPF checks the DataContext property of that element If it s null, WPF searches up the element tree looking for the first data context that isn t null. <StackPanel> <TextBlock Text="{Binding Source={x:Static SystemFonts.IconFontFamily}, Path=Source}"/> <TextBlock Text="{Binding Source={x:Static SystemFonts.IconFontFamily}, Path=LineSpacing}"/> <TextBlock Text="{Binding Source={x:Static SystemFonts.IconFontFamily}, Path=FamilyTypefaces[0].Style}"/> <TextBlock Text="{Binding Source={x:Static SystemFonts.IconFontFamily}, Path=FamilyTypefaces[0].Weight}"/> </StackPanel> 152 <StackPanel DataContext="{x:Static SystemFonts.IconFontFamily}"> <TextBlock Text="{Binding Path=Source}"/> <TextBlock Text="{Binding Path=LineSpacing}"/> <TextBlock Text="{Binding Path=FamilyTypefaces[0].Style}"/> <TextBlock Text="{Binding Path=FamilyTypefaces[0].Weight}"/> </StackPanel>

153 Binding to a Collection of Objects To support collection binding, the ItemsControl class defines the three key properties: ItemsSource points to the collection of objects DisplayMemberPath identifiers the property that will be used to create the display text for each item ItemTemplate accepts a data template that will be used to create the visual appearance of each item <Window x:class="wpfapplication1.data.bindingtocollection" xmlns=" xmlns:x=" xmlns:src="clr-namespace:wpfapplication1" Title="BindingToCollection" Height="300" Width="300"> <StackPanel> <StackPanel.Resources> <src:customers x:key="customers"/> </StackPanel.Resources> <ListBox ItemsSource="{StaticResource customers}" DisplayMemberPath="LastName"/> </StackPanel> </Window> 153

154 ObservableCollection<T> WPF provides the ObservableCollection<T> class, which is a built-in implementation of a data collection that implements the INotifyCollectionChanged interface This interface exposes the CollectionChanged event, an event that should be raised whenever the underlying collection changes 154

155 Data Conversion The value converter is responsible for converting the source data just before it s displayed in the target In the case of a two-way binding, it is also responsible for converting the new target value just before it s applied back to the source Value converters can be used to: Format data to a string representation Create a specific type of WPF object Conditionally alter a property in an element based on the bound data 155

156 Creating a Value Converter 1. Create a class that implements IValueConverter 2. Add the ValueConversion attribute to the class declaration, and specify the destination and target data types 3. Implement a Convert method that changes data from its original format to its display format 4. Implement a ConvertBack method that does the reverse and changes a value from display format to its native format <Window x:class="wpfapplication1.data.dateconverterexample" xmlns=" xmlns:x=" xmlns:src="clr-namespace:wpfapplication1" xmlns:sys="clr-namespace:system;assembly=mscorlib"> <Grid> <Grid.Resources> <src:dateconverter x:key="dateconverter"/> </Grid.Resources> <TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding Source={x:Static sys:datetime.now}, Converter={StaticResource dateconverter}}"/> </Grid> </Window> 156

157 Value Converter Example 157 [ValueConversion(typeof(DateTime), typeof(string))] public class DateConverter : IValueConverter { public object Convert(object value, Type targettype, object parameter, CultureInfo culture) { DateTime date = (DateTime)value; return date.toshortdatestring(); } } public object ConvertBack(object value, Type targettype, object parameter, CultureInfo culture) { string strvalue = value.tostring(); DateTime resultdatetime; if (DateTime.TryParse(strValue, out resultdatetime)) { return resultdatetime; } return value; }

158 Validation WPF provides a validation feature that works closely with the data binding system There are two ways of handling validation Simply throw an exception from a property set procedure The ExceptionValidationRule is a prebuilt validation rule that tells WPF to report all exceptions (by default, WPF ignores any exception thrown when setting a property) Define validation at the binding level This gives the flexibility to use the same validation regardless of the input control 158

159 Validation Example 159 <TextBox Grid.Column="1" Grid.Row="1" Width="200" Margin="5,5,50,5" Style="{StaticResource highlightvalidationerror}" Validation.ErrorTemplate="{StaticResource validationtemplate}"> <TextBox.Text> <Binding Path="SomeDate" UpdateSourceTrigger="PropertyChanged"> <Binding.ValidationRules> <ExceptionValidationRule /> </Binding.ValidationRules> </Binding> </TextBox.Text> </TextBox>

160 <ControlTemplate Windows Presentation Foundation x:key="validationtemplate"> <DockPanel> Validation <Border Name="validationBorder" Example BorderBrush="Red" cont. BorderThickness="2" Padding="1" CornerRadius="3"> <Border.Resources> <Storyboard x:key="_blink"> <ColorAnimationUsingKeyFrames AutoReverse="True" BeginTime="00:00:00" Storyboard.TargetName="validationBorder" Storyboard.TargetProperty="(Border.BorderBrush).(SolidColorBrush.Color)" RepeatBehavior="Forever"> <SplineColorKeyFrame KeyTime="00:00:00.5" Value="#00FF0000"/> </ColorAnimationUsingKeyFrames> </Storyboard> </Border.Resources> <Border.Triggers> [...] </Border.Triggers> <AdornedElementPlaceholder/> </Border> <src:exclamation Width="25" Height="25" /> </DockPanel> </ControlTemplate> <Style x:key="highlightvalidationerror" > <Style.Triggers> <Trigger Property="Validation.HasError" Value="True"> <Setter Property="TextBox.Background" Value="Pink" /> <Setter Property="TextBox.ToolTip" Value="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=(Validation.Errors)[0].ErrorContent}"/> </Trigger> </Style.Triggers> </Style> 160

161 Data Template A data template is a chunk of XAML markup that defines how a bound data object should be displayed Two types of controls support data templates: Content controls support data templates through the ContentTemplate property List controls support data templates through the ItemTemplate property <ListBox Name="personsListBox"> <ListBox.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding Path=FirstName}"></TextBlock> </DataTemplate> </ListBox.ItemTemplate> </ListBox> 161

This tutorial has been designed for all those readers who want to learn WPF and to apply it instantaneously in different type of applications.

This tutorial has been designed for all those readers who want to learn WPF and to apply it instantaneously in different type of applications. About the Tutorial WPF stands for Windows Presentation Foundation. It is a powerful framework for building Windows applications. This tutorial explains the features that you need to understand to build

More information

Windows Presentation Foundation

Windows Presentation Foundation Windows Presentation Foundation C# Programming April 18 Windows Presentation Foundation WPF (code-named Avalon ) is the graphical subsystem of the.net 3.0 Framework It provides a new unified way to develop

More information

WPF Shapes. WPF Shapes, Canvas, Dialogs 1

WPF Shapes. WPF Shapes, Canvas, Dialogs 1 WPF Shapes WPF Shapes, Canvas, Dialogs 1 Shapes are elements WPF Shapes, Canvas, Dialogs 2 Shapes draw themselves, no invalidation or repainting needed when shape moves, window is resized, or shape s properties

More information

Introduction to C#, Visual Studio and Windows Presentation Foundation

Introduction to C#, Visual Studio and Windows Presentation Foundation Introduction to C#, Visual Studio and Windows Presentation Foundation Lecture #3: C#, Visual Studio, and WPF Joseph J. LaViola Jr. Fall 2008 Fall 2008 CAP 6938 Topics in Pen-Based User Interfaces Joseph

More information

ComponentOne. Windows for WPF

ComponentOne. Windows for WPF ComponentOne Windows for WPF Copyright 1987-2012 GrapeCity, Inc. All rights reserved. ComponentOne, a division of GrapeCity 201 South Highland Avenue, Third Floor Pittsburgh, PA 15206 USA Internet: info@componentone.com

More information

Windows Store App Development

Windows Store App Development Windows Store App Development C# AND XAML PETE BROWN 11 MANNING SHELTER ISLAND contents preface xvii acknowledgments xx about this book xxii about the author xxviii. about the cover illustration xxix If

More information

Windows Presentation Foundation Using C#

Windows Presentation Foundation Using C# Windows Presentation Foundation Using C# Student Guide Revision 4.0 Object Innovations Course 4135 Windows Presentation Foundation Using C# Rev. 4.0 Student Guide Information in this document is subject

More information

Pro WPF in C# 2008. Windows Presentation Foundation with.net 3.5 SECOND EDITION. Matthew MacDonald. Apress 8. [] rj G

Pro WPF in C# 2008. Windows Presentation Foundation with.net 3.5 SECOND EDITION. Matthew MacDonald. Apress 8. [] rj G Pro WPF in C# 2008 Windows Presentation Foundation with.net 3.5 SECOND EDITION [] rj G Matthew MacDonald Apress 8 Contents About the Author About the Technical Reviewer Acknowledgments Introduction xxii

More information

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer. Windows 10 Apps Development

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer. Windows 10 Apps Development About the Tutorial Welcome to Windows 10 tutorial. This tutorial is designed for people who want to learn how to develop apps meant for Windows 10. After completing it, you will have a better understating

More information

Windows Presentation Foundation Tutorial 1

Windows Presentation Foundation Tutorial 1 Windows Presentation Foundation Tutorial 1 PDF: Tutorial: A http://billdotnet.com/wpf.pdf http://billdotnet.com/dotnet_lecture/dotnet_lecture.htm Introduction 1. Start Visual Studio 2008, and select a

More information

Microsoft Virtual Labs. Building Windows Presentation Foundation Applications - C# - Part 1

Microsoft Virtual Labs. Building Windows Presentation Foundation Applications - C# - Part 1 Microsoft Virtual Labs Building Windows Presentation Foundation Applications - C# - Part 1 Table of Contents Building Windows Presentation Foundation Applications - C# - Part 1... 1 Exercise 1 Creating

More information

Important New Concepts in WPF

Important New Concepts in WPF CHAPTER 3 Important New Concepts in WPF IN THIS CHAPTER. Logical and Visual Trees. Dependency Properties. Routed Events. Commands. A Tour of the Class Hierarchy To finish Part I of this book, and before

More information

Top 50 WPF Interview Questions

Top 50 WPF Interview Questions Top 50 WPF Interview Questions 1. What is WPF? WPF is the latest presentation API by Microsoft Windows. It is 2D and 3D graphic engine. Its capabilities include:- All the common user controls. For example,

More information

JavaFX Session Agenda

JavaFX Session Agenda JavaFX Session Agenda 1 Introduction RIA, JavaFX and why JavaFX 2 JavaFX Architecture and Framework 3 Getting Started with JavaFX 4 Examples for Layout, Control, FXML etc Current day users expect web user

More information

1. WPF Tutorial Page 1 of 431 wpf-tutorial.com

1. WPF Tutorial Page 1 of 431 wpf-tutorial.com 1. WPF Tutorial Page 1 of 431 1.1. About WPF 1.1.1. What is WPF? WPF, which stands for Windows Presentation Foundation, is Microsoft's latest approach to a GUI framework, used with the.net framework. But

More information

Pro WPF 4.5 in C# Matthew MacDonald. Apress*

Pro WPF 4.5 in C# Matthew MacDonald. Apress* Pro WPF 4.5 in C# Matthew MacDonald Apress* Contents a About the Author a About the Technical Reviewer xxvi xxvii» Acknowledgments xxviii a Introduction xxix a Part I: Fundamentals 1 a Chapter 1: Introducing

More information

Introduction to Windows Presentation Foundation

Introduction to Windows Presentation Foundation Page 1 of 41 2009 Microsoft Corporation. All rights reserved. Windows Presentation Foundation Windows Presentation Foundation (WPF) is a next-generation presentation system for building Windows client

More information

In this session, we will explain some of the basics of word processing. 1. Start Microsoft Word 11. Edit the Document cut & move

In this session, we will explain some of the basics of word processing. 1. Start Microsoft Word 11. Edit the Document cut & move WORD PROCESSING In this session, we will explain some of the basics of word processing. The following are the outlines: 1. Start Microsoft Word 11. Edit the Document cut & move 2. Describe the Word Screen

More information

How To Write A Powerpoint 2.5.2.2 (For A Powerbook) On A Microsoft Powerbook 2.4.2 On A Windows 7.5 (For Windows 7) On An Ipa 2.3.

How To Write A Powerpoint 2.5.2.2 (For A Powerbook) On A Microsoft Powerbook 2.4.2 On A Windows 7.5 (For Windows 7) On An Ipa 2.3. Pro WPF in C# 2010: Windows Presentation Foundation in.net 4 Matthew MacDonald Apress s Contents About the Author xxvi About the Technical Reviewer xxvii Acknowledgments xxviii Introduction xxix Chapter

More information

Windows Presentation Foundation: What, Why and When

Windows Presentation Foundation: What, Why and When Windows Presentation Foundation: What, Why and When A. WHY WPF: WPF is framework to build application for windows. It is designed for.net influenced by modern display technologies like HTML and Flash and

More information

Microsoft Word 2010. Quick Reference Guide. Union Institute & University

Microsoft Word 2010. Quick Reference Guide. Union Institute & University Microsoft Word 2010 Quick Reference Guide Union Institute & University Contents Using Word Help (F1)... 4 Window Contents:... 4 File tab... 4 Quick Access Toolbar... 5 Backstage View... 5 The Ribbon...

More information

Data Binding with WPF: Binding to XML

Data Binding with WPF: Binding to XML Data Binding with WPF: Binding to XML Excerpted from WPF in Action with Visual Studio 2008 EARLY ACCESS EDITION Arlen Feldman and Maxx Daymon MEAP Release: July 2007 Softbound print: October 2008 (est.),

More information

Mapping to the Windows Presentation Framework

Mapping to the Windows Presentation Framework Mapping to the Windows Presentation Framework This section maps the main IFML concepts to the.net Windows Presentation Framework (WFP). Windows Presentation Framework (WPF) is a part of.net Framework by

More information

Creating Interactive PDF Forms

Creating Interactive PDF Forms Creating Interactive PDF Forms Using Adobe Acrobat X Pro Information Technology Services Outreach and Distance Learning Technologies Copyright 2012 KSU Department of Information Technology Services This

More information

Creating Web Pages with Microsoft FrontPage

Creating Web Pages with Microsoft FrontPage Creating Web Pages with Microsoft FrontPage 1. Page Properties 1.1 Basic page information Choose File Properties. Type the name of the Title of the page, for example Template. And then click OK. Short

More information

CaptainCasa. CaptainCasa Enterprise Client. CaptainCasa Enterprise Client. Feature Overview

CaptainCasa. CaptainCasa Enterprise Client. CaptainCasa Enterprise Client. Feature Overview Feature Overview Page 1 Technology Client Server Client-Server Communication Client Runtime Application Deployment Java Swing based (JRE 1.6), generic rich frontend client. HTML based thin frontend client

More information

Nintex Forms 2013 Help

Nintex Forms 2013 Help Nintex Forms 2013 Help Last updated: Friday, April 17, 2015 1 Administration and Configuration 1.1 Licensing settings 1.2 Activating Nintex Forms 1.3 Web Application activation settings 1.4 Manage device

More information

Windows Presentation Foundation (WPF)

Windows Presentation Foundation (WPF) 50151 - Version: 4 05 July 2016 Windows Presentation Foundation (WPF) Windows Presentation Foundation (WPF) 50151 - Version: 4 5 days Course Description: This five-day instructor-led course provides students

More information

Handout: Word 2010 Tips and Shortcuts

Handout: Word 2010 Tips and Shortcuts Word 2010: Tips and Shortcuts Table of Contents EXPORT A CUSTOMIZED QUICK ACCESS TOOLBAR... 2 IMPORT A CUSTOMIZED QUICK ACCESS TOOLBAR... 2 USE THE FORMAT PAINTER... 3 REPEAT THE LAST ACTION... 3 SHOW

More information

Microsoft Publisher 2010 What s New!

Microsoft Publisher 2010 What s New! Microsoft Publisher 2010 What s New! INTRODUCTION Microsoft Publisher 2010 is a desktop publishing program used to create professional looking publications and communication materials for print. A new

More information

Content Author's Reference and Cookbook

Content Author's Reference and Cookbook Sitecore CMS 6.5 Content Author's Reference and Cookbook Rev. 110621 Sitecore CMS 6.5 Content Author's Reference and Cookbook A Conceptual Overview and Practical Guide to Using Sitecore Table of Contents

More information

Using Microsoft Word. Working With Objects

Using Microsoft Word. Working With Objects Using Microsoft Word Many Word documents will require elements that were created in programs other than Word, such as the picture to the right. Nontext elements in a document are referred to as Objects

More information

MS Word 2007 practical notes

MS Word 2007 practical notes MS Word 2007 practical notes Contents Opening Microsoft Word 2007 in the practical room... 4 Screen Layout... 4 The Microsoft Office Button... 4 The Ribbon... 5 Quick Access Toolbar... 5 Moving in the

More information

Bitrix Site Manager 4.1. User Guide

Bitrix Site Manager 4.1. User Guide Bitrix Site Manager 4.1 User Guide 2 Contents REGISTRATION AND AUTHORISATION...3 SITE SECTIONS...5 Creating a section...6 Changing the section properties...8 SITE PAGES...9 Creating a page...10 Editing

More information

Responsive Web Design Creative License

Responsive Web Design Creative License Responsive Web Design Creative License Level: Introduction - Advanced Duration: 16 Days Time: 9:30 AM - 4:30 PM Cost: 2197 Overview Web design today is no longer just about cross-browser compatibility.

More information

Hypercosm. Studio. www.hypercosm.com

Hypercosm. Studio. www.hypercosm.com Hypercosm Studio www.hypercosm.com Hypercosm Studio Guide 3 Revision: November 2005 Copyright 2005 Hypercosm LLC All rights reserved. Hypercosm, OMAR, Hypercosm 3D Player, and Hypercosm Studio are trademarks

More information

Hands-On Lab. Building Applications in Silverlight 4 Module 8: Advanced OOB and MEF. Event Administrator Dashboard

Hands-On Lab. Building Applications in Silverlight 4 Module 8: Advanced OOB and MEF. Event Administrator Dashboard Hands-On Lab Building Applications in Silverlight 4 Module 8: Advanced OOB and MEF 1 P a g e Contents Introduction... 3 Exercise 1: Sending Email... 4 Exercise 2: Custom Window Chrome... 7 Configuring

More information

Using Adobe Dreamweaver CS4 (10.0)

Using Adobe Dreamweaver CS4 (10.0) Getting Started Before you begin create a folder on your desktop called DreamweaverTraining This is where you will save your pages. Inside of the DreamweaverTraining folder, create another folder called

More information

Overview of Microsoft Office Word 2007

Overview of Microsoft Office Word 2007 Overview of Microsoft Office What Is Word Processing? Office is a word processing software application whose purpose is to help you create any type of written communication. A word processor can be used

More information

3. Add and delete a cover page...7 Add a cover page... 7 Delete a cover page... 7

3. Add and delete a cover page...7 Add a cover page... 7 Delete a cover page... 7 Microsoft Word: Advanced Features for Publication, Collaboration, and Instruction For your MAC (Word 2011) Presented by: Karen Gray (kagray@vt.edu) Word Help: http://mac2.microsoft.com/help/office/14/en-

More information

PowerPoint 2007 Basics Website: http://etc.usf.edu/te/

PowerPoint 2007 Basics Website: http://etc.usf.edu/te/ Website: http://etc.usf.edu/te/ PowerPoint is the presentation program included in the Microsoft Office suite. With PowerPoint, you can create engaging presentations that can be presented in person, online,

More information

MAX 2006 Beyond Boundaries

MAX 2006 Beyond Boundaries MAX 2006 Beyond Boundaries Matthew Boles Adobe Customer Training Technical Lead RI101H: Your First RIA with Flex 2 October 24-26, 2006 1 What You Will Learn Functionality of the Flex product family The

More information

Introduction to Microsoft Word 2008

Introduction to Microsoft Word 2008 1. Launch Microsoft Word icon in Applications > Microsoft Office 2008 (or on the Dock). 2. When the Project Gallery opens, view some of the available Word templates by clicking to expand the Groups, and

More information

BUILDING APPLICATIONS USING C# AND.NET FRAMEWORK (OBJECT-ORIENTED PROGRAMMING, X428.6)

BUILDING APPLICATIONS USING C# AND.NET FRAMEWORK (OBJECT-ORIENTED PROGRAMMING, X428.6) Technology & Information Management Instructor: Michael Kremer, Ph.D. Class 9 Professional Program: Data Administration and Management BUILDING APPLICATIONS USING C# AND.NET FRAMEWORK (OBJECT-ORIENTED

More information

Building and Using Web Services With JDeveloper 11g

Building and Using Web Services With JDeveloper 11g Building and Using Web Services With JDeveloper 11g Purpose In this tutorial, you create a series of simple web service scenarios in JDeveloper. This is intended as a light introduction to some of the

More information

SQL Server 2005: Report Builder

SQL Server 2005: Report Builder SQL Server 2005: Report Builder Table of Contents SQL Server 2005: Report Builder...3 Lab Setup...4 Exercise 1 Report Model Projects...5 Exercise 2 Create a Report using Report Builder...9 SQL Server 2005:

More information

Copyright 2006 TechSmith Corporation. All Rights Reserved.

Copyright 2006 TechSmith Corporation. All Rights Reserved. TechSmith Corporation provides this manual as is, makes no representations or warranties with respect to its contents or use, and specifically disclaims any expressed or implied warranties or merchantability

More information

Quick Start Guide. Microsoft Publisher 2013 looks different from previous versions, so we created this guide to help you minimize the learning curve.

Quick Start Guide. Microsoft Publisher 2013 looks different from previous versions, so we created this guide to help you minimize the learning curve. Quick Start Guide Microsoft Publisher 2013 looks different from previous versions, so we created this guide to help you minimize the learning curve. Quick Access Toolbar Add your favorite commands to the

More information

Dashboards and Presentation Design User Guide SAP BusinessObjects 4.0 Feature Pack 3

Dashboards and Presentation Design User Guide SAP BusinessObjects 4.0 Feature Pack 3 Dashboards and Presentation Design User Guide SAP BusinessObjects 4.0 Feature Pack 3 Copyright 2011 SAP AG. All rights reserved.sap, R/3, SAP NetWeaver, Duet, PartnerEdge, ByDesign, SAP BusinessObjects

More information

Microsoft Word 2010 Prepared by Computing Services at the Eastman School of Music July 2010

Microsoft Word 2010 Prepared by Computing Services at the Eastman School of Music July 2010 Microsoft Word 2010 Prepared by Computing Services at the Eastman School of Music July 2010 Contents Microsoft Office Interface... 4 File Ribbon Tab... 5 Microsoft Office Quick Access Toolbar... 6 Appearance

More information

Umbraco v4 Editors Manual

Umbraco v4 Editors Manual Umbraco v4 Editors Manual Produced by the Umbraco Community Umbraco // The Friendly CMS Contents 1 Introduction... 3 2 Getting Started with Umbraco... 4 2.1 Logging On... 4 2.2 The Edit Mode Interface...

More information

Name of chapter & details

Name of chapter & details Course Title Course Code Modern Application Development CE913 (Elective III) Theory : 03 Course Credit Practical : 01 Tutorial : 00 Course Learning Outcomes Credits : 04 On the completion of the course,

More information

CONTENTM WEBSITE MANAGEMENT SYSTEM. Getting Started Guide

CONTENTM WEBSITE MANAGEMENT SYSTEM. Getting Started Guide CONTENTM WEBSITE MANAGEMENT SYSTEM Getting Started Guide Table of Contents CONTENTM WEBSITE MANAGEMENT SYSTEM... 1 GETTING TO KNOW YOUR SITE...5 PAGE STRUCTURE...5 Templates...5 Menus...5 Content Areas...5

More information

Adobe Dreamweaver CC 14 Tutorial

Adobe Dreamweaver CC 14 Tutorial Adobe Dreamweaver CC 14 Tutorial GETTING STARTED This tutorial focuses on the basic steps involved in creating an attractive, functional website. In using this tutorial you will learn to design a site

More information

Hands-On Lab. Building a Data-Driven Master/Detail Business Form using Visual Studio 2010. Lab version: 1.0.0. Last updated: 12/10/2010.

Hands-On Lab. Building a Data-Driven Master/Detail Business Form using Visual Studio 2010. Lab version: 1.0.0. Last updated: 12/10/2010. Hands-On Lab Building a Data-Driven Master/Detail Business Form using Visual Studio 2010 Lab version: 1.0.0 Last updated: 12/10/2010 Page 1 CONTENTS OVERVIEW... 3 EXERCISE 1: CREATING THE APPLICATION S

More information

Creating Hyperlinks & Buttons InDesign CS6

Creating Hyperlinks & Buttons InDesign CS6 Creating Hyperlinks & Buttons Adobe DPS, InDesign CS6 1 Creating Hyperlinks & Buttons InDesign CS6 Hyperlinks panel overview You can create hyperlinks so that when you export to Adobe PDF or SWF in InDesign,

More information

Create Charts in Excel

Create Charts in Excel Create Charts in Excel Table of Contents OVERVIEW OF CHARTING... 1 AVAILABLE CHART TYPES... 2 PIE CHARTS... 2 BAR CHARTS... 3 CREATING CHARTS IN EXCEL... 3 CREATE A CHART... 3 HOW TO CHANGE THE LOCATION

More information

Implementing multi-user multi-touch scenarios using WPF in Windows* 8 Desktop Apps

Implementing multi-user multi-touch scenarios using WPF in Windows* 8 Desktop Apps Implementing multi-user multi-touch scenarios using WPF in Windows* 8 Desktop Apps Summary In this paper we walk through a sample application (in this case a game that quizzes people on the Periodic Table)

More information

Developing Website Using Tools

Developing Website Using Tools 7 Developing Website Using Tools 7.1 INTRODUCTION A number of Software Packages are available in market for creating a website. Among popular softwares are Dreamweaver, Microsoft FrontPage and Flash. These

More information

Microsoft Word 2010 Tutorial

Microsoft Word 2010 Tutorial 1 Microsoft Word 2010 Tutorial Microsoft Word 2010 is a word-processing program, designed to help you create professional-quality documents. With the finest documentformatting tools, Word helps you organize

More information

Microsoft FrontPage 2003

Microsoft FrontPage 2003 Information Technology Services Kennesaw State University Microsoft FrontPage 2003 Information Technology Services Microsoft FrontPage Table of Contents Information Technology Services...1 Kennesaw State

More information

What s New in QuarkXPress 8

What s New in QuarkXPress 8 What s New in QuarkXPress 8 LEGAL NOTICES 2008 Quark Inc. as to the content and arrangement of this material. All rights reserved. 1986 2008 Quark Inc. and its licensors as to the technology. All rights

More information

Word Processing programs and their uses

Word Processing programs and their uses Word Processing programs and their uses An application that provides extensive tools for creating all kinds of text based programs. They are not limited to working with text and enable you to add images

More information

DataPA OpenAnalytics End User Training

DataPA OpenAnalytics End User Training DataPA OpenAnalytics End User Training DataPA End User Training Lesson 1 Course Overview DataPA Chapter 1 Course Overview Introduction This course covers the skills required to use DataPA OpenAnalytics

More information

Application Developer Guide

Application Developer Guide IBM Maximo Asset Management 7.1 IBM Tivoli Asset Management for IT 7.1 IBM Tivoli Change and Configuration Management Database 7.1.1 IBM Tivoli Service Request Manager 7.1 Application Developer Guide Note

More information

Understanding In and Out of XAML in WPF

Understanding In and Out of XAML in WPF Understanding In and Out of XAML in WPF 1. What is XAML? Extensible Application Markup Language and pronounced zammel is a markup language used to instantiate.net objects. Although XAML is a technology

More information

Business Objects Version 5 : Introduction

Business Objects Version 5 : Introduction Business Objects Version 5 : Introduction Page 1 TABLE OF CONTENTS Introduction About Business Objects Changing Your Password Retrieving Pre-Defined Reports Formatting Your Report Using the Slice and Dice

More information

CA Plex and Microsoft Windows Presentation

CA Plex and Microsoft Windows Presentation CA Plex and Microsoft Windows Presentation Foundation (WPF) A Technology Preview 8C Rob Layzell CA Aligned LEFT ON COVER ONLY Terms of This Presentation This presentation was based on current information

More information

70-511. Microsoft Windows Apps Dev w/microsoft.net Framework 4. http://www.officialcerts.com

70-511. Microsoft Windows Apps Dev w/microsoft.net Framework 4. http://www.officialcerts.com http://www.officialcerts.com 70-511 Microsoft Windows Apps Dev w/microsoft.net Framework 4 OfficialCerts.com is a reputable IT certification examination guide, study guides and audio exam provider. We

More information

Visual Studio 2008: Windows Presentation Foundation

Visual Studio 2008: Windows Presentation Foundation Visual Studio 2008: Windows Presentation Foundation Course 6460A: Three days; Instructor-Led Introduction This three-day instructor-led course provides students with the knowledge and skills to build and

More information

Module One: Getting Started... 6. Opening Outlook... 6. Setting Up Outlook for the First Time... 7. Understanding the Interface...

Module One: Getting Started... 6. Opening Outlook... 6. Setting Up Outlook for the First Time... 7. Understanding the Interface... 2 CONTENTS Module One: Getting Started... 6 Opening Outlook... 6 Setting Up Outlook for the First Time... 7 Understanding the Interface...12 Using Backstage View...14 Viewing Your Inbox...15 Closing Outlook...17

More information

Microsoft Expression Web Quickstart Guide

Microsoft Expression Web Quickstart Guide Microsoft Expression Web Quickstart Guide Expression Web Quickstart Guide (20-Minute Training) Welcome to Expression Web. When you first launch the program, you ll find a number of task panes, toolbars,

More information

PORTAL ADMINISTRATION

PORTAL ADMINISTRATION 1 Portal Administration User s Guide PORTAL ADMINISTRATION GUIDE Page 1 2 Portal Administration User s Guide Table of Contents Introduction...5 Core Portal Framework Concepts...5 Key Items...5 Layouts...5

More information

Sharing a Screen, Documents or Whiteboard in Cisco Unified MeetingPlace

Sharing a Screen, Documents or Whiteboard in Cisco Unified MeetingPlace Sharing a Screen, Documents or Whiteboard in Cisco Unified MeetingPlace Release: 7.0 Revision Date: December 9, 2009 1:29 pm This section describes how to use the features in the Cisco Unified MeetingPlace

More information

Desktop, Web and Mobile Testing Tutorials

Desktop, Web and Mobile Testing Tutorials Desktop, Web and Mobile Testing Tutorials * Windows and the Windows logo are trademarks of the Microsoft group of companies. 2 About the Tutorial With TestComplete, you can test applications of three major

More information

Microsoft PowerPoint Tutorial

Microsoft PowerPoint Tutorial Microsoft PowerPoint Tutorial Contents Starting MS PowerPoint... 1 The MS PowerPoint Window... 2 Title Bar...2 Office Button...3 Saving Your Work... 3 For the first time... 3 While you work... 3 Backing

More information

San Joaquin County Office of Education Career & Technical Education Web Design ~ Course Outline CBEDS#: 4601

San Joaquin County Office of Education Career & Technical Education Web Design ~ Course Outline CBEDS#: 4601 Web Design Course Outline I II 1 Course Content 5 5 Student Evaluation Employment Opportunities 2 XHTML 10 10 Creating an HTML Document Formatting Text with HTML Adding Graphics with Multimedia Using forms

More information

Microsoft Access 2010 Part 1: Introduction to Access

Microsoft Access 2010 Part 1: Introduction to Access CALIFORNIA STATE UNIVERSITY, LOS ANGELES INFORMATION TECHNOLOGY SERVICES Microsoft Access 2010 Part 1: Introduction to Access Fall 2014, Version 1.2 Table of Contents Introduction...3 Starting Access...3

More information

Relationships in WPF Applications

Relationships in WPF Applications Chapter 15 Relationships in WPF Applications Table of Contents Chapter 15... 15-1 Relationships in WPF Applications... 15-1 One-To-Many Combo Box to List Box... 15-1 One-To-Many Relationships using Properties...

More information

Introduction to dobe Acrobat XI Pro

Introduction to dobe Acrobat XI Pro Introduction to dobe Acrobat XI Pro Introduction to Adobe Acrobat XI Pro is licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. To view a copy of this

More information

7 th Annual LiveText Collaboration Conference. Advanced Document Authoring

7 th Annual LiveText Collaboration Conference. Advanced Document Authoring 7 th Annual LiveText Collaboration Conference Advanced Document Authoring Page of S. La Grange Road, nd Floor, La Grange, IL 6055-455 -866-LiveText (-866-548-3839) edu-solutions@livetext.com Page 3 of

More information

SMART Ink 1.5. Windows operating systems. Scan the following QR code to view the SMART Ink Help on your smart phone or other mobile device.

SMART Ink 1.5. Windows operating systems. Scan the following QR code to view the SMART Ink Help on your smart phone or other mobile device. SMART Ink 1.5 Windows operating systems User s guide Scan the following QR code to view the SMART Ink Help on your smart phone or other mobile device. Trademark notice SMART Ink, SMART Notebook, SMART

More information

How to create a Flash banner advert in DrawPlus X2

How to create a Flash banner advert in DrawPlus X2 How to create a Flash banner advert in DrawPlus X2 Open DrawPlus X2 and choose Start New: Keyframe Animation Select WebPlus 10 Flash Banner and click on Open The work area should look like the screenshot.

More information

Introduction to the Visual Studio.NET IDE

Introduction to the Visual Studio.NET IDE 2 Introduction to the Visual Studio.NET IDE Objectives To be introduced to the Visual Studio.NET Integrated Development Environment (IDE). To become familiar with the types of commands contained in the

More information

Intellect Platform - Tables and Templates Basic Document Management System - A101

Intellect Platform - Tables and Templates Basic Document Management System - A101 Intellect Platform - Tables and Templates Basic Document Management System - A101 Interneer, Inc. 4/12/2010 Created by Erika Keresztyen 2 Tables and Templates - A101 - Basic Document Management System

More information

How To Write A Cq5 Authoring Manual On An Ubuntu Cq 5.2.2 (Windows) (Windows 5) (Mac) (Apple) (Amd) (Powerbook) (Html) (Web) (Font

How To Write A Cq5 Authoring Manual On An Ubuntu Cq 5.2.2 (Windows) (Windows 5) (Mac) (Apple) (Amd) (Powerbook) (Html) (Web) (Font Adobe CQ5 Authoring Basics Print Manual SFU s Content Management System SFU IT Services CMS Team ABSTRACT A summary of CQ5 Authoring Basics including: Setup and Login, CQ Interface Tour, Versioning, Uploading

More information

Create a Poster Using Publisher

Create a Poster Using Publisher Contents 1. Introduction 1. Starting Publisher 2. Create a Poster Template 5. Aligning your images and text 7. Apply a background 12. Add text to your poster 14. Add pictures to your poster 17. Add graphs

More information

Access 2007 Creating Forms Table of Contents

Access 2007 Creating Forms Table of Contents Access 2007 Creating Forms Table of Contents CREATING FORMS IN ACCESS 2007... 3 UNDERSTAND LAYOUT VIEW AND DESIGN VIEW... 3 LAYOUT VIEW... 3 DESIGN VIEW... 3 UNDERSTAND CONTROLS... 4 BOUND CONTROL... 4

More information

Silverlight for Windows Embedded Graphics and Rendering Pipeline 1

Silverlight for Windows Embedded Graphics and Rendering Pipeline 1 Silverlight for Windows Embedded Graphics and Rendering Pipeline 1 Silverlight for Windows Embedded Graphics and Rendering Pipeline Windows Embedded Compact 7 Technical Article Writers: David Franklin,

More information

Microsoft Visual Studio Integration Guide

Microsoft Visual Studio Integration Guide Microsoft Visual Studio Integration Guide MKS provides a number of integrations for Integrated Development Environments (IDEs). IDE integrations allow you to access MKS Integrity s workflow and configuration

More information

SQL Server 2005 Reporting Services (SSRS)

SQL Server 2005 Reporting Services (SSRS) SQL Server 2005 Reporting Services (SSRS) Author: Alex Payne and Brian Welcker Published: May 2005 Summary: SQL Server 2005 Reporting Services is a key component of SQL Server 2005. Reporting Services

More information

Generating Automated Test Scripts for AltioLive using QF Test

Generating Automated Test Scripts for AltioLive using QF Test Generating Automated Test Scripts for AltioLive using QF Test Author: Maryam Umar Contents 1. Introduction 2 2. Setting up QF Test 2 3. Starting an Altio application 3 4. Recording components 5 5. Performing

More information

Microsoft Excel 2010 Tutorial

Microsoft Excel 2010 Tutorial 1 Microsoft Excel 2010 Tutorial Excel is a spreadsheet program in the Microsoft Office system. You can use Excel to create and format workbooks (a collection of spreadsheets) in order to analyze data and

More information

Contents. Introduction. Chapter 1 Some Hot Tips to Get You Started. Chapter 2 Tips on Working with Strings and Arrays..

Contents. Introduction. Chapter 1 Some Hot Tips to Get You Started. Chapter 2 Tips on Working with Strings and Arrays.. Contents Introduction How to Use This Book How to Use the Tips in This Book Code Naming Conventions Getting the Example Source Code Getting Updates to the Example Code Contacting the Author Chapter 1 Some

More information

Contents. Microsoft Office 2010 Tutorial... 1

Contents. Microsoft Office 2010 Tutorial... 1 Microsoft Office 2010 Tutorial Contents Microsoft Office 2010 Tutorial... 1 Find your way through long documents with the new Document Navigation pane and Search... 4 Adjust the spaces between lines or

More information

A SharePoint Developer Introduction. Hands-On Lab. Lab Manual SPCHOL306 Using Silverlight with the Client Object Model VB

A SharePoint Developer Introduction. Hands-On Lab. Lab Manual SPCHOL306 Using Silverlight with the Client Object Model VB A SharePoint Developer Introduction Hands-On Lab Lab Manual SPCHOL306 Using Silverlight with the Client Object Model VB This document is provided as-is. Information and views expressed in this document,

More information

Microsoft Migrating to Word 2010 from Word 2003

Microsoft Migrating to Word 2010 from Word 2003 In This Guide Microsoft Word 2010 looks very different, so we created this guide to help you minimize the learning curve. Read on to learn key parts of the new interface, discover free Word 2010 training,

More information

Asset Track Getting Started Guide. An Introduction to Asset Track

Asset Track Getting Started Guide. An Introduction to Asset Track Asset Track Getting Started Guide An Introduction to Asset Track Contents Introducing Asset Track... 3 Overview... 3 A Quick Start... 6 Quick Start Option 1... 6 Getting to Configuration... 7 Changing

More information

Word Processing. with. OpenOffice Writer

Word Processing. with. OpenOffice Writer Word Processing with OpenOffice Writer W o r d P r o c e s s i n g w i t h O p e n O f f i c e W r i t e r P a r t 1 Part I: Introduction to OpenOffice Writer OpenOffice Writer is an open-source free software

More information

Acrobat X Pro Accessible Forms and Interactive Documents

Acrobat X Pro Accessible Forms and Interactive Documents Contents 2 PDF Form Fields 2 Acrobat Form Wizard 5 Enter Forms Editing Mode Directly 5 Create Form Fields Manually 6 Forms Editing Mode 8 Form Field Properties 11 Editing or Modifying an Existing Form

More information