wpf for beginners - learn in 3 days

41
WPF for Beginners Udayakumar Mathivanan MCP,MCTS Certified Scrum Master

Upload: udaya-kumar

Post on 07-May-2015

740 views

Category:

Technology


0 download

DESCRIPTION

WPF For Beginners - Learn in 3 days - Udayakumar Mathivanan

TRANSCRIPT

Page 1: WPF For Beginners  - Learn in 3 days

WPF for Beginners

Udayakumar Mathivanan MCP,MCTS

Certified Scrum Master

Page 2: WPF For Beginners  - Learn in 3 days

2

Agenda

− Why WPF ?− WPF Architecture− Demo’s− WPF Design Patterns− Understanding MVVM Pattern− Layouts− Loading XAML at Runtime

Page 3: WPF For Beginners  - Learn in 3 days

3

Why WPF?− Windows Presentation Foundation,

part of WinFx, is a completely new presentation framework replacing User, GDI, GDI+, Win32.

− Uses DirectX instead of Old Graphics System.

− Competes with HTML, Macromedia Flash, SVG.

− Give developers the tools to make rich quality applications, but also Flash like websites.

Page 4: WPF For Beginners  - Learn in 3 days

4

Why WPF ?− Uses Direct3D rendering which employs

graphics cards to render the output on the screen.

− Drawing in the form will be smooth and also there is a chance to utilize the hardware capabilities installed in your machine.

− traditional GDI forms application, won’t use advanced graphics capabilities and hence Windows Forms application will always be inefficient in comparison to WPF

Page 5: WPF For Beginners  - Learn in 3 days

Why WPF ?

− GDI Windows forms application uses Operating system controls to build its application.

− WPF controls are actually drawn over the screen, and hence you can customize controls totally and modify their behavior when required.

Page 6: WPF For Beginners  - Learn in 3 days

6

WPF Architecture− WPF is actually a set of assemblies that build up the entire

framework. These assemblies can be categorized as:− Managed Layer

− built using a number of assemblies. These assemblies build up the WPF framework, communicate with lower level unmanaged API to render its content. The few assemblies that comprise the WPF framework are:

− PresentationFramework.dll: Creates the top level elements like layout panels, controls, windows, styles, etc.

− PresentationCore.dll: It holds base types such as UIElement, Visual from which all shapes and controls are Derived in PresentationFramework.dll.

− WindowsBase.dll: They hold even more basic elements which are capable of being used outside the WPF environment like Dispatcher object, Dependency Objects

− UnManaged Layer (milcore.dll)− The unmanaged layer of WPF is called milcore or Media Integration Library

Core. It basically translates the WPF higher level objects like layout panels, buttons, animation, etc. into textures that Direct3D expects. It is the main rendering engine of WPF.

− WindowsCodecs.dll: This is another low level API which is used for imaging support in WPF applications.

Core API− Direct3D: It is the low level API in which the graphics of WPF is rendered.

− User32: It is the primary core API which every program uses. It actually manages memory and process separation.

− GDI & Device Drivers: GDI and Device Drivers are specific to the operating system which is also used from the application to access low level APIs.

Page 7: WPF For Beginners  - Learn in 3 days

WPF Architecture

Page 8: WPF For Beginners  - Learn in 3 days

8

WPF Architecture− Separation of Appearance and Behavior.

− WPF separates the appearance of an user interface from its behavior. The appearance is generally specified in the Extensible Application Markup Language (XAML), the behavior is implemented in a managed programming language like C# or Visual Basic.

− The two parts are tied together by databinding, events and commands. The separation of appearance and behavior brings the following benefits:

− Appearance and behaviour are loosely coupled− Designers and developers can work on separate models.− Graphical design tools can work on simple XML documents

instead of parsing code.

Page 9: WPF For Beginners  - Learn in 3 days

9

WPF Architecture

− WPF combines application UIs, 2D graphics, 3D graphics, documents and multimedia into one single framework.

− Its vector based rendering engine uses hardware acceleration of modern graphic cards. This makes the UI faster, scalable and resolution independent.

Page 10: WPF For Beginners  - Learn in 3 days

10

WPF Development Tools

− Microsoft provides two development tools for WPF applications.

− Visual Studio, made for developers and the other is Expression Blend made for designers.

− Visual Studio is good in code and XAML editing, it has a rare support for all the graphical stuff like gradients, template editing, animation, etc.

− Blend covers the graphical part very well but it has (still) rare support for code and XAML editing.

Page 11: WPF For Beginners  - Learn in 3 days

11

WPF Features

Page 12: WPF For Beginners  - Learn in 3 days

12

WPF Features

− Device Independent Pixel (DPI)− WPF introduces Device

Independent DPI Settings for the applications built with it. For a window, it is very important to calculate how many Dots Per inch(DPI) the screen could draw. This is generally dependent on the hardware device and operating system in which the application runs and also how the DPI settings is applied on the Device. 

− WPF addresses this issue and makes it independent of DPI settings of the computer.

Page 13: WPF For Beginners  - Learn in 3 days

WPF Features

− Built-In Support for Graphics and Animation− WPF applications as being rendered within

DirectX environment, it has major support of graphics and animation capabilities. A separate set of classes are there which specifically deal with animation effects and graphics. 

− Resource based Approach for every control− can store styles, controls, animations, and even

any object as resource. Thus each resource will be declared once when the form loads itself, and you may associate them to the controls. You can maintain a full hierarchy of styles in a separate file called ResourceDictionary

Page 14: WPF For Beginners  - Learn in 3 days

Demo’s : The Basics

− Hello World− The Application Object− The content model− EventHandling− Databinding

Page 15: WPF For Beginners  - Learn in 3 days

15

Patterns to design a good WPF architecture

− Model-View-View-Model Pattern − Dependency Injection − Undo/Redo − DelegateCommand

Page 16: WPF For Beginners  - Learn in 3 days

How the MVVM pattern became convenient• MVVM was designed to make use of data

binding functions in WPF to better facilitate the separation of view layer development from the rest of the pattern by removing virtually all GUI code (“code-behind”) from the view layer.

• WPF has a very powerful databinding feature, that provides an easy one-way or two-way synchronization of properties.

Page 17: WPF For Beginners  - Learn in 3 days

Difference between MVVM, MVP and MVC

− MVC - Model-View-Controller− The MVC pattern consists of one controller that

directly gets all user input. Depending of the kind of input, it shows up a different view or modifies the data in the model.

− The model and the view are created by the controller.

− The view only knows about the model, but the model does not know about any other objects.

Page 18: WPF For Beginners  - Learn in 3 days

Difference between MVVM, MVP and MVC− MVP - Model-View-Presenter

− In the MVP pattern, the view gets the user input and forwards it to the presenter.

− The presenter than modifies the view or the model depending on the type of user action.

− The view and the presenter are tightly coupled. − There is a bidirectional one-to-one relation between them.

The model does not know about the presenter. The view itself is passive, thats why it's called presenter pattern, since the presenter pushes the data into the view. This pattern is often seen in WinForms and early WPF applications.

Page 19: WPF For Beginners  - Learn in 3 days

Difference between MVVM, MVP and MVC

− MVVM - Model-View-ViewModel− The model-view-viewmodel is a typically WPF

pattern. It consists of a view, that gets all the user input and forwards it to the viewmodel, typically by using commands.

− The view actively pulls the data from the viewmodel by using databinding. The model does not know about the view model.

Page 20: WPF For Beginners  - Learn in 3 days

What's MVVM?

• is an architectural pattern created by John Gossman from WPF team

• is a variation of MVC pattern• is similar to Martin Fowler’s

PresentationModel pattern• WPF Data Binding & Commanding

Page 21: WPF For Beginners  - Learn in 3 days

Motivation and benefits

• Testabiltiy ( ViewModel is easier to unit test than code-behind or event driven code)

• Clear seperation between UX designer and developer

• Increases the "Blendability" of your view• Model never needs to be changed to

support changes to the view• ViewModel rarely needs to be changed

to support changes to the view• No duplicated code to update views

Page 22: WPF For Beginners  - Learn in 3 days

MVVM

• View knows ViewModel• ViewModel knows Models• But not vice versa.

View ViewModel Model

Page 23: WPF For Beginners  - Learn in 3 days

View

• represents the user interface that the user will see.

• can be a user control or Data Template

• shouldn't contain any logic that you want to test

• Keep the view as simple as possible.

Page 24: WPF For Beginners  - Learn in 3 days

View Model

• An abstraction of View• Connector between View and Model• Keep View State, Value Conversion• No strong or weak (via Interface)

reference of View• Make VM as testable as possible (e.g.

no call to Singleton class)• No Control related Stuff in VM

Page 25: WPF For Beginners  - Learn in 3 days

Model

• can be Data Model, DTO, POCO, auto-generated proxy of domain class and UI Model based on how you want to have the separation between Domain Service and Presentation Layer

• No reference to ViewModel

Page 26: WPF For Beginners  - Learn in 3 days

26

Layout− Layout of controls is critical to an applications

usability. Arranging controls based on fixed pixel coordinates may work for an limited environment, but as soon as you want to use it on different screen resolutions or with different font sizes it will fail.

− WPF provides a rich set built-in layout panels that help you to avoid the common pitfalls.

− five most popular layout panels of WPF: − Grid Panel− Stack Panel− Dock Panel− Wrap Panel− Canvas Panel

Page 27: WPF For Beginners  - Learn in 3 days

Layout− Best Practices− Avoid fixed positions - use the Alignment properties

in combination with Margin to position elements in a panel

− Avoid fixed sizes - set the Width and Height of elements to Auto whenever possible.

− Don't abuse the canvas panel to layout elements. Use it only for vector graphics.

− Use a StackPanel to layout buttons of a dialog− Use a GridPanel to layout a static data entry form.

Create a Auto sized column for the labels and a Star sized column for the TextBoxes.

− Use an ItemControl with a grid panel in a DataTemplate to layout dynamic key value lists. Use the SharedSize feature to synchronize the label widths.

Page 28: WPF For Beginners  - Learn in 3 days

Hello World

− XAML example

<Page xmlns="http://schemas.microsoft.com/winfx/avalon/2005" xmlns:x="http://schemas.microsoft.com/winfx/xaml/2005">

<TextBlock>Hello World!</TextBlock>

</Page>

Page 29: WPF For Beginners  - Learn in 3 days

29

Application Object

− Application object acts as container for more complex applications− MainWindow− Application events

like− Startup & Shutdown

public class MyApp : Application{ [STAThread] static void Main(string[] args) { MyApp app = new MyApp(); app.Startup += app.OnApplicationStartup; app.Run(args); }

void OnApplicationStartup(object sender,

StartupEventArgs e) { Window w = new Window(); w.Title = "Mark says: Hello World!"; w.Show(); }

}

Page 30: WPF For Beginners  - Learn in 3 days

Content Model

− WPF offers strong separation of behaviour (API) and presentation

− Behaviour (API) consists of− Commands, Properties, Events & Methods

− Presentation of controls is controlled by− Nested content− Templates

Page 31: WPF For Beginners  - Learn in 3 days

StackPanel example<Window x:Class="Demo4.Content.Window1" xmlns="http://schemas.microsoft.com/winfx/avalon/2005" xmlns:x="http://schemas.microsoft.com/winfx/xaml/2005" Title="Demo4.Content"> <StackPanel Orientation=“Vertical"> <Button Name="button1">Just text</Button> <Button Name="button2"> <Image Source="banner.jpg" Name="image1" Width="100"/> </Button> <Button Name="button3"> <StackPanel Orientation="Vertical"> <TextBlock>Just text<LineBreak/>The next line</TextBlock> <Image Source="banner.jpg" Name="image1" Width="100"/> </StackPanel> </Button> </StackPanel></Window>

Page 32: WPF For Beginners  - Learn in 3 days

32

Grid example<Window x:Class="Demo4.Content.Window1" xmlns="http://schemas.microsoft.com/winfx/avalon/2005" xmlns:x="http://schemas.microsoft.com/winfx/xaml/2005" Title="Demo4.Content"> <Grid ShowGridLines="True"> <Grid.ColumnDefinitions> <ColumnDefinition/> <ColumnDefinition/> <ColumnDefinition/> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition/> <RowDefinition/> <RowDefinition/> </Grid.RowDefinitions> <TextBlock Grid.Column="0" Grid.Row="0">Top left</TextBlock> <TextBlock Grid.Column="1" Grid.Row="1">Middle</TextBlock> <TextBlock Grid.Column="2" Grid.Row="2">LRight</TextBlock> </Grid></Window>

Page 33: WPF For Beginners  - Learn in 3 days

Eventhandling

− Most significant feature is ‘Event Bubbling’ called ‘EventRouting’− RoutedEventArgs

− e.Handled = true;

void innerButton_Click(object sender, RoutedEventArgs e)

{

MessageBox.Show("Hello SDN!");

e.Handled = true;

}

Page 34: WPF For Beginners  - Learn in 3 days

Databinding

− New ways of databinding?− Important features:

− Window.DataContext− StaticResources− DataTemplates− ObservableCollection

− Tip: Use INotifyPropertyChanged

Page 35: WPF For Beginners  - Learn in 3 days

Databinding example<StackPanel Name="pnlMain"> <TextBlock>Name: </TextBlock> <TextBox Name="txtName" Text="{Binding Path=Name}“/> <TextBlock>City:</TextBlock> <TextBox Name="txtCity" Text="{Binding Path=City}“/> <StackPanel Orientation="Horizontal"> <Button Name="btnPrevious“ Click="btnPrevious_Click">&lt;</Button> <Button Name="btnNext“ Click="btnNext_Click">&gt;</Button> </StackPanel> <ListBox Name="lstCustomers“ IsSynchronizedWithCurrentItem="True“ ItemsSource="{Binding}"/></StackPanel>

Page 36: WPF For Beginners  - Learn in 3 days

CollectionView− WPF has a powerful data binding

infrastructure. It allows you to bind almost any kind of collection directly to a view.

− But when it comes to sorting, filtering and grouping the support of the collections is rare. That's the point where the CollectionView comes into play.

− A collection view is a wrapper around a collection that provides the following additional features:

− Navigation− Sorting− Filtering− Grouping

Page 37: WPF For Beginners  - Learn in 3 days

Loading XAML at Runtime− Add controls to your WPF window at

runtime.− public Window1()

{  InitializeComponent();  LoadRuntimeControls();}

− private void myButton_Click(object sender, RoutedEventArgs e){  MessageBox.Show("I have been clicked");}

− private void LoadRuntimeControls(){  //Load button from XML file  FileStream fileStream = new FileStream(@"c:\RuntimeContent.xml", FileMode.Open);  DependencyObject dependencyObject = XamlReader.Load(fileStream) as DependencyObject;  this.Content = dependencyObject;

−   //Find the button and wireup a click event  Button myButton = LogicalTreeHelper.FindLogicalNode(dependencyObject, "btnOnTheFly") as Button;  myButton.Click+=new RoutedEventHandler(myButton_Click);}

Page 38: WPF For Beginners  - Learn in 3 days

Loading XAML at Runtime− // Create the Button. Button originalButton

= new Button(); originalButton.Height = 50; originalButton.Width = 100; originalButton.Background = Brushes.AliceBlue; originalButton.Content = "Click Me";

− // Save the Button to a string.  − string savedButton =

XamlWriter.Save(originalButton); − // Load the button StringReader

stringReader = new StringReader(savedButton);

− XmlReader xmlReader = XmlReader.Create(stringReader);

− Button readerLoadButton = (Button)XamlReader.Load(xmlReader);

Page 39: WPF For Beginners  - Learn in 3 days

Few things to know before you start WPF programming..− What is Meant by Dispatcher & Thread

Affinity?− What is Visual Tree and Logical Tree?− Why RoutedEvent?− Why DependencyObject is Used?− What about Hardware Acceleration

and Graphics Rendering Tiers in WPF?

Page 40: WPF For Beginners  - Learn in 3 days

Q & A

Page 41: WPF For Beginners  - Learn in 3 days

Time to fill the feedback and Say “Big Thanks”.