420 likes | 932 Views
WPF for Beginners. Udayakumar Mathivanan MCP,MCTS Certified Scrum Master. Agenda. Why WPF ? WPF Architecture Demo’s WPF Design Patterns Understanding MVVM Pattern Layouts Loading XAML at Runtime. Why WPF?.
E N D
WPF for Beginners Udayakumar Mathivanan MCP,MCTS Certified Scrum Master
Agenda • Why WPF ? • WPF Architecture • Demo’s • WPF Design Patterns • Understanding MVVM Pattern • Layouts • Loading XAML at Runtime
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.
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
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.
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.
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.
WPFArchitecture • 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.
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.
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.
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
Demo’s : The Basics • Hello World • The Application Object • The content model • EventHandling • Databinding
Patterns to design a good WPF architecture • Model-View-View-Model Pattern • Dependency Injection • Undo/Redo • DelegateCommand
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.
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.
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.
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.
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
Motivation and benefits • Testabiltiy ( ViewModel is easier to unit test than code-behind or event driven code) • Clearseperationbetween 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
MVVM • View knows ViewModel • ViewModel knows Models • But not vice versa. View ViewModel Model
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.
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
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
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
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.
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>
Application Object 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(); } } • Application object acts as container for more complex applications • MainWindow • Application events like • Startup & Shutdown
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
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>
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> <TextBlockGrid.Column="0" Grid.Row="0">Top left</TextBlock> <TextBlockGrid.Column="1" Grid.Row="1">Middle</TextBlock> <TextBlockGrid.Column="2" Grid.Row="2">LRight</TextBlock> </Grid></Window>
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; }
Databinding • New ways of databinding? • Important features: • Window.DataContext • StaticResources • DataTemplates • ObservableCollection • Tip: Use INotifyPropertyChanged
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"><</Button> <Button Name="btnNext“ Click="btnNext_Click">></Button> </StackPanel> <ListBox Name="lstCustomers“IsSynchronizedWithCurrentItem="True“ItemsSource="{Binding}"/></StackPanel>
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
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 fileFileStreamfileStream = new FileStream(@"c:\RuntimeContent.xml", FileMode.Open);DependencyObjectdependencyObject = 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);}
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 StringReaderstringReader = new StringReader(savedButton); • XmlReaderxmlReader = XmlReader.Create(stringReader); • Button readerLoadButton = (Button)XamlReader.Load(xmlReader);
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?