Windows Presentation Foundation Maximilian Knor Developer Evangelist Developer and Plattform Group...

Post on 03-Jan-2016

220 views 0 download

Transcript of Windows Presentation Foundation Maximilian Knor Developer Evangelist Developer and Plattform Group...

Windows Presentation FoundationWindows Presentation Foundation

Maximilian KnorDeveloper EvangelistDeveloper and Plattform GroupMicrosoft Österreich

max.knor@microsoft.com http://blogs.msdn.com/knom/

MSDN Briefings – OrganisationMSDN Briefings – Organisation

Monthly technical briefingsCurrently released technologyYour current needs

Invitation / Registration / Feedbackhttp://blogs.msdn.com/msdnat http://blogs.msdn.com/talk

Well, what I am doing here?

TopicsTopics

Windows Presentation Foundation

Overview2D

Controls and Layout

Styles, Templates & ResourcesData BindingAnimationInterop and Migration

Why WPF? Another UI Framework?Why WPF? Another UI Framework?

Aren‘t these some classicsApp flickers on re-sizeOverlay controls and videosThemeing und styling

What‘s the cause?Win32 has limitsGraphics rendered by CPU

The WPF ApproachThe WPF Approach

Unify UI, Documents, MediaIntegrated development

New Windows infrastructure Vector based graphicsUse display hardware (D3D)Built-in UI patterns

Designers and toolsBringing designers into the processDeclarative programming models

.NET 3.0.NET 3.0

Operating System

.NET Framework 2.0

.NET Framework 3.0

WindowsPresentationFoundation

WindowsCommunication

Foundation

WindowsWorkflow

Foundation

WindowsCard Space

WPFUser

Experience

WCFUnified

Messaging

WFFederated Workflow

CSFederated

Identity

WPF Programming ModelWPF Programming Model

Button b1 = new Button();b1.Content = "OK";b1.Background = new SolidColorBrush(Colors.LightBlue);b1.Width = new Length(100);

<Button Width="100px"> OK <Button.Background> HorizontalGradient= "White LtBlue" </Button.Background></Button>

Dim b1 As New Buttonb1.Content = "OK"b1.Background = New SolidColorBrush(Colors.LightBlue)b1.Width = New Length(100)

Separate UI and behaviorDo you know ASP.NET Similar but more powerful

XAMLWhat, Not How!Creates object hierarchy

Designer Developer

Developer Designer CollaborationDeveloper Designer Collaboration

XAMLXAML

Extensible Applications Markup Language

<Button Name="button1" Background="Red">

Click Me!</Button>

Button button1 = new Button();button1.Content = "Click Me!";button1.Background = new SolidColorBrush(

Colors.Red);

Properties as Attributes or ElementsProperties as Attributes or Elements

<Button Content="Click Me!" Background="LightGreen" />

<Button> <Button.Background> LightGreen </Button.Background> Click Me!</Button>

Attached PropertiesAttached Properties

<Canvas> <Button Canvas.Top="30" Canvas.Left="40"> Click Me! </Button></Canvas>

Markup ExtensionsMarkup Extensions

<Button Name="button1"> <Button.Style> <StaticResource ResourceKey="key" /> </Button.Style> Click Me!</Button>

<Button Name="button1" Style="{StaticResource key}" Content="Click Me" />

TopicsTopics

Windows Presentation Foundation

Overview2D

Controls and Layout

Styles, Templates & ResourcesData BindingAnimationInterop and Migration

ShapesShapes

Elements of UI treeJust like controls and other elements

Rectangle

Ellipse

Polyline

Polygon

Path

DemoDemo

2D Shapes

Shapes and CodeShapes and Code

Shapes accessible from code behindJust like any element

Change appearance by setting propertiesScreen is automatically updated

<Ellipse Fill="Yellow" Name="myEllipse" StrokeThickness="7" Stroke="Black" Width="100" Height="100" />

// ...in code behind

myEllipse.Width = 200;

BrushesBrushes

Specifies how shape is filledUsed for properties throughout WPF

<Rectangle Fill="Red" Width="200" Height="100" />

Linear/RadialGradientBrushLinear/RadialGradientBrush

Fills across a range of colorsEnables interesting visual effects

ImageBrushImageBrush

<TextBlock FontSize="72" FontFamily="Arial Black"> <TextBlock.Foreground>

<ImageBrush ImageSource="c:\Windows\Blue Lace 16.bmp" />

</TextBlock.Foreground> Hello, World!</TextBlock>

Composability: DrawingBrushComposability: DrawingBrush

Fill with vector imageScalable

Composability: VisualBrushComposability: VisualBrush

Fill with any UI elementMakes certain design tricks easy

Reflection of UIUse as 3D surface texture

OpacityMaskOpacityMask

Apply opacity to any visual using any Brush

TransformationsTransformations

Any element can be transformedScaling, rotation, moving

Optionally affects layoutLayoutTransformRenderTransform

Included into hit testing

DemoDemo

Transformations

TopicsTopics

Windows Presentation Foundation

Overview2D

Controls and Layout

Styles, Templates & ResourcesData BindingAnimationInterop and Migration

Class HierarchyClass Hierarchy

Dependency PropertyDependency Property

public class MyDependencyObject : DependencyObject{ public static readonly DependencyProperty SomeStateProperty = DependencyProperty.Register("SomeState", typeof(String), typeof(MyDependencyObject));  public string SomeState { get { return (string)this.GetValue(SomeStateProperty); } set { this.SetValue(SomeStateProperty, value); } }}

Layout ControlsLayout Controls

StackPanelWrapPanelCanvasDockPanelGrid...

WPF PositioningWPF Positioning

Absolute PositioningX / Y, Width / Height

Relative PositioningNO X/Y, Width/HeightMarginAlignment

<Button Margin="20,10,20,10">Hallo Welt</Button>

WPF Positioning - AlignmentWPF Positioning - Alignment

HorizontalAlignmentStretch, Left, Right, Center

VerticalAlignmentStretch, Top, Center, Bottom

<Button HorizontalAlignment="Stretch" VerticalAlignment="Stretch"> Hallo Welt</Button>

<Button HorizontalAlignment="Left"

VerticalAlignment="Bottom">

Hallo Welt</Button>

Simple ControlsSimple Controls

PasswordBoxScrollBarProgressBarSliderTextBoxRichTextBox...

Content ControlsContent Controls

ButtonRepeatButtonToggleButtonCheckBoxRadioButtonLabelFrameListBoxItemStatusBarItemScollBarViewer

ToolTipUserControlWindowNavigationWindow...

DemoDemo

Controls

EventsEvents

Routed Event Handling

Routing StrategyTunneling, Bubbling, Direct

EventsEvents

Create Routed Events

public static readonly RoutedEvent TapEvent = EventManager.RegisterRoutedEvent("Tap", RoutingStrategy.Bubble,

typeof(RoutedEventHandler), typeof(MyButtonSimple));

public event RoutedEventHandler Tap { add { AddHandler(TapEvent, value); }remove { RemoveHandler(TapEvent, value); }

}

EventsEvents

Event notationPreviewXxx – TunnelledXxx - Bubbled

Base Class RoutedEventArgs

Attached Events

DemoDemo

Routed Event Handling

Headered Content ControlsHeadered Content Controls

• Content Control with additional header

• Expander

• MenuItem

• GroupBox

• TabItem

• Usw.

Items ControlsItems Controls

• Container for multiple items (list)

• ListBox• ComboBox

• Menu• ContextMenu• StatusBar

• TreeView• TabControl

• Usw.

CommandsCommands

Controls define a command

CommandBindings define the handler

<Button Command="ApplicationCommands.New"> <Image Source="toolbargraphics/New.bmp" /> </Button>

<Window.CommandBindings> <CommandBinding Command="ApplicationCommands.New" Executed="FileNew" CanExecute="CanFileNew" /></Window.CommandBindings>

DemoDemo

TabControl, Listbox, Toolbar, Commands

TopicsTopics

Windows Presentation Foundation

Overview2D

Controls and Layout

Styles, Templates & ResourcesData BindingAnimationInterop and Migration

Designer

Developer

Ske

leto

nPrototype

&

Experiment

Feedback from Customers

Fin

al

Pro

du

ct

Design

Development Process

Styling & Templates

Styles are about setting properties…Styles are about setting properties…

Setting Properties

Trigger

Animations

Template

Styles

Lookless Controls and TemplatesLookless Controls and Templates

Control implies behaviour

Probably supplies default lookDesigner free to supply new look

Styling and ResourcesStyling and Resources

Style rarely defined inlineTend to be reused for consistency

Usually defined as resources

Resource DictionariesResource Dictionaries

Simple Key, Value collectionFrameworkElement.Resources

<Grid> <Grid.Resources> <Style x:Key="dapper"> <Setter Property="Background" Value="LimeGreen" /> </Style> </Grid.Resources>

...

<Button Style="{StaticResource dapper}">Click</Button>

Resource HierarchyResource Hierarchy

System Resources

Application Resources

ElementResources

ElementResources

ElementResources

Window/PageResources

Window/PageResources

ElementResources

Application Resources

<Window> <Window.Resources> ... </Window.Resources>

<Grid> <Grid.Resources> ... </Grid.Resources>

<ListBox> <ListBox.Resources> ... </ListBox.Resources> </ListBox> </Grid></Window>

Application ResourcesApplication Resources

Styles and templatesShared graphics

<Application x:Class="ResourcePlay.MyApp" xmlns="http://schemas.microsoft.com/winfx/avalon/2005" xmlns:x="http://schemas.microsoft.com/winfx/xaml/2005">

<Application.Resources> <Style x:Key="dapper"> <Setter Property="Background" Value="LimeGreen" /> </Style> </Application.Resources></Application>

Page/Window ResourcesPage/Window Resources

Utility elementsData sourcesConverters

Page-specific templates

Element-Specific ResourcesElement-Specific Resources

Locally-scoped Styles and templates

<Window ...> ... <Grid> <Grid.Resources> <Style TargetType="{x:Type TextBlock}"> <Setter Property="Margin" Value="5" /> </Style> </Grid.Resources>

... </Grid> ...</Window>

Automatic Styles/TemplatesAutomatic Styles/Templates

Most resources must use x:KeyOptional with Styles and Data Templates

Can use TargetType or DataType insteadApplied to target automatically – no reference required

<Window.Resources> <Style TargetType="{x:Type TextBlock}"> <Setter Property="Margin" Value="5" /> </Style></Window.Resources>

DemoDemo

Styles

System ResourcesSystem Resources

SystemColors – Colors and BrushesSystemFontsSystemParameters (sizes, settings)

<Rectangle Height="50" Width="100" Fill="{x:Static SystemColors.ControlBrush}" />

<!-- Better – responds to config changes --><Rectangle Height="50" Width="100" Fill="{DynamicResource {x:Static SystemColors.ControlBrushKey}}" />

Resources and Code-BehindResources and Code-Behind

FindResource

SetResourceReference

Change resource value with indexersomeElem.Resources["foo"] = bar;

Initializing from code-behind not so goodMust set before referencing XAML loadedOK for app resources, less good otherwise