WPF

Introduction to Windows Presentation Foundation

Overview:

The Windows Presentation Foundation is Microsoft next generation UI framework to create applications using rich user experience. It supports in .net 3.0 or higher.
WPF is combination of below features.


  ·         Vector based Rendering
  ·         Hardware accelerated(3D Graphics)
  ·         Declarative UI With XAML
  ·         Multi Media Support
  ·         Skinning Support
  ·         XPS Documents
  ·         3D Programming
  ·         Highly Composable
  ·         Animations and time lines
  ·         Powerful Binding
  ·         Resolution independent
  ·         Highly Customizable

Vector Based Rendering: The vector based rendering engine uses hardware acceleration of modern graphic cards. This makes the UI faster, scalable and resolution independent.
Hardware accelerated: Actually WPF rendering automatically detects how much hardware acceleration is supported by the current system and adjusts itself accordingly. The graphics rendering detects the appropriate tier for rendering the output accordingly.
For hardware rendering, few things that have most of the impact are:

o    Video RAM: This determines the size and number of buffers that the application might use to render its output.
o    Pixel Shader: It is a graphics utility which calculates effects on per pixel basis.
o    Vertex Shader: It is a graphics processing utility that performs mathematical calculations on Vertex of the output. They are used to add special effects to objects in 3D environment.
o    MultiTexture Blending: This is a special function that allows you to apply two or more textures on the same object in 3D.

Now the rendering engine of WPF determines which tier is appropriate for the current application and applies therendering tiers accordingly.
1.    TIER 0: No graphics hardware acceleration takes place, rather everything is rendered using Software. Any version of DirectX 9 or less is capable of rendering this output.
2.    TIER 1: Partial hardware and software rendering. You might use Directx9 or greater to use this tier.
3.    TIER 2: Full hardware acceleration. Directx9 or above can render this output.

Declarative UI with XAML: XAML stands for Extensible Application Markup Language. Its a simple language based on XML to create and initialize .NET objects with hierarchical relations. Although it was originally invented for WPF it can by used to create any kind of object trees.
Today XAML is used to create user interfaces in WPF, Silverlight, declare workflows in WF and for electronic paper in the XPS standard.
All classes in WPF have parameterless constructors and make excessive usage of properties. That is done to make it perfectly fit for XML languages like XAML.

Advantages of XAML: To declare UI we can do in XAML can also be done in code. XAML its just another way to create and initialize objects. You can use WPF without using XAML. It's up to you if you want to declare it in XAML or write it in code.

Declare your UI in XAML has some advantages:
  • XAML code is short and clear to read
  • Separation of designer code and logic
  • Graphical design tools like Expression Blend require XAML as source.
  • The separation of XAML and UI logic allows it to clearly separate the roles of designer and developer.
XAML vs. Code
As an example we build a simple StackPanel with a textblock and a button in XAML and compare it to the same code in C#.
    Margin="20">Welcome to the World of XAML
    



The same expressed in C# will look like this:


StackPanel stackPanel = new StackPanel(); this.Content = stackPanel;  // Create the TextBlockTextBlock textBlock = new TextBlock(); textBlock.Margin = new Thickness(10); textBlock.Text = "Welcome to the World of XAML"; stackPanel.Children.Add(textBlock);  // Create the ButtonButton button = new Button(); button.Margin= new Thickness(20); button.Content = "OK"; stackPanel.Children.Add(button);


Multi Media Support: Images, video, and audio are media-rich ways of conveying information and user experiences.

Images

Images, which include icons, backgrounds, and even parts of animations, are a core part of most applications. Because you frequently need to use images, WPF exposes the ability to work with them in a variety of ways. The following illustration shows just one of those ways.





When user click on Browse button then a dialog box opens and ask to select a media file which needs to be played. When user click on Play button then media plays file from beginning, when the user click on stop button then current file will be stop and when user click on Pause button then it will be pause.

Xmal Code:


   <MediaElement Height="431" HorizontalAlignment="Left" LoadedBehavior="Manual" UnloadedBehavior="Stop" Margin="12,12,0,0" x:Name="mediaPlayer1" VerticalAlignment="Top" Width="794" />
            <Button Content="Play" Height="29" HorizontalAlignment="Left" Margin="31,466,0,0" x:Name="btnPlay" VerticalAlignment="Top" Width="149" Click="btnPlay_Click" />
            <Button Content="Pause" Height="29" HorizontalAlignment="Left" Margin="216,466,0,0" x:Name="btnPause" VerticalAlignment="Top" Width="156" Click="btnPause_Click" />
            <Button Content="Stop" Height="29" HorizontalAlignment="Left" Margin="407,466,0,0" x:Name="btnStop" VerticalAlignment="Top" Width="163" Click="btnStop_Click" />
            <Button Content="Browse" Height="29" HorizontalAlignment="Right" Margin="0,466,48,0" x:Name="btnBrowse" VerticalAlignment="Top" Width="151" Click="btnBrowse_Click" />


C# Code ;

   //



        /// On the click event of browse button we browse a file that
        /// needs to be played by using OpenFileDialog box and then play
        /// that file by calling Play() method of mediaelement control.
        ///

        ///
        ///
        private void btnBrowse_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            if (ofd.ShowDialog().Value)
            {
                string fileName = ofd.FileName;
                mediaPlayer1.Source = new Uri(fileName);
                mediaPlayer1.Play();
            }
        }

        ///



        /// On the click event of button control we play loaded media
        /// by calling Play() method of MediaElement control.
        ///

        ///
        ///
        private void btnPlay_Click(object sender, RoutedEventArgs e)
        {
            if (mediaPlayer1.HasVideo)
            {
                mediaPlayer1.Play();
            }
        }

        ///



        /// On the click event of Pause button we pause the playing media
        /// by calling Pause method.
        ///

        ///
        ///

        private void btnPause_Click(object sender, RoutedEventArgs e)
        {
            if (mediaPlayer1.HasVideo)
            {
                if (mediaPlayer1.IsLoaded)
                {
                    mediaPlayer1.Pause();
                }
            }
        }

        ///



        /// By calling the stop button  we pause the media which stops.
        ///

        ///
        ///

        private void btnStop_Click(object sender, RoutedEventArgs e)
        {
            if (mediaPlayer1.HasVideo)
            {
                mediaPlayer1.Stop();
            }
        }


Skinning Support:
The Windows Presentation Foundation provides great support for UI Skinning. The skinning can be re-style either compile time or runtime.
A resource is an object that can be reused in different places in your application. Examples of resources include brushes and styles. This overview describes how to use resources in XAML. You can also create and access resources by using code, or interchangeably between code and Extensible Application Markup Language (XAML)
We have two types of Resources.
o    Static Resources.
o    Dynamic Resource
Static Resource:
·         Your application design concentrates most of all of its resources into page or application level resource dictionaries. Static resource references are not reevaluated based on runtime behaviors such as reloading a page, and therefore there can be some performance benefit to avoiding large numbers of dynamic resource references when they are not necessary per your resource and application design.
·         You are setting the value of a property that is not on a DependencyObject or a Freezable.
·         You are creating a resource dictionary that will be compiled into a DLL, and packaged as part of the application or shared between applications.
·         You are creating a theme for a custom control, and are defining resources that are used within the themes. For this case, you typically do not want the dynamic resource reference lookup behavior, you instead want the static resource reference behavior so that the lookup is predictable and self-contained to the theme. With a dynamic resource reference, even a reference within a theme is left unevaluated until runtime, and there is a chance that when the theme is applied, some local element will redefine a key that your theme is trying to reference, and the local element will fall prior to the theme itself in the lookup. If that happens, your theme will not behave in an expected manner.
·         You are using resources to set large numbers of dependency properties. Dependency properties have effective value caching as enabled by the property system, so if you provide a value for a dependency property that can be evaluated at load time, the dependency property does not have to check for a reevaluated expression and can return the last effective value. This technique can be a performance benefit.
·         You want to change the underlying resource for all consumers, or you want to maintain separate writable instances for each consumer by using the x:Shared Attribute.





<Window.Resources>
            <SolidColorBrush x:Key="MyBrush" Color="Black"/>
            <Style TargetType="Border" x:Key="PageBackground">
                <Setter Property="Background" Value="Yellow"/>
            </Style>
            <Style TargetType="TextBlock" x:Key="TitleText">
                <Setter Property="Background" Value="Blue"/>
                <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"/>
                <Setter Property="FontWeight" Value="Bold"/>
                <Setter Property="Margin" Value="0,3,10,0"/>
            </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>
                    <Ellipse DockPanel.Dock="Top" HorizontalAlignment="Left" Width="100" Height="100" Fill="{StaticResource MyBrush}" Margin="40" />
                </DockPanel>
            </Border>
        </StackPanel>
Dynamic Resources:
·         The value of the resource depends on conditions that are not known until runtime. This includes system resources, or resources that are otherwise user settable. For example, you can create setter values that refer to system properties, as exposed by SystemColors, SystemFonts, orSystemParameters. These values are truly dynamic because they ultimately come from the runtime environment of the user and operating system. You might also have application-level themes that can change, where page-level resource access must also capture the change.
·         You are creating or referencing theme styles for a custom control.
·         You intend to adjust the contents of a ResourceDictionary during an application lifetime.
·         You have a complicated resource structure that has interdependencies, where a forward reference may be required. Static resource references do not support forward references, but dynamic resource references do support them because the resource does not need to be evaluated until runtime, and forward references are therefore not a relevant concept.
·         You are referencing a resource that is particularly large from the perspective of a compile or working set, and the resource might not be used immediately when the page loads. Static resource references always load from XAML when the page loads; however, a dynamic resource reference does not load until it is actually used.
·         You are creating a style where setter values might come from other values that are influenced by themes or other user settings.
·         You are applying resources to elements that might be reparented in the logical tree during application lifetime. Changing the parent also potentially changes the resource lookup scope, so if you want the resource for a reparented element to be reevaluated based on the new scope, always use a dynamic resource reference.

Xaml Code:
<StackPanel>
<Button x:Name="btn" Content="Click Me" Click="Button_Click" Background="{DynamicResource brush}" Height="100" Width="100" />



C# Code;

</StackPanel private void Button_Click(object sender, RoutedEventArgs e)
        {
            this.btn.SetResourceReference(BackgroundProperty, "brush");
        }

XPS Documents:
 XML Paper Specification (XPS) document is a package that contains one or more fixed-documents along with all the resources and information required for rendering. XPS is also the native Windows Vista print spool file format. An XpsDocument is stored in standard ZIP dataset, and can include a combination of XML and binary components, such as image and font files. PackageRelationships are used to define the dependencies between the content and the resources required to fully render the document. The XpsDocument design provides a single, high-fidelity document solution that supports multiple uses:

·         Reading, writing, and storing fixed-document content and resources as a single, portable, and easy-to-distribute file.
·         Displaying documents with the XPS Viewer application.
·         Outputting documents in the native print spool output format of Windows Vista.
·         Routing documents directly to an XPS-compatible printer.

WPF divides documents into two broad categories based on their intended use; these document categories are termed

·         Fixed documents.
·         Flow documents.

Fixed-format document with read access for user text selection, keyboard navigation, and search.

<FixedDocument>
  Pages
</FixedDocument>           

The following example demonstrates declarative usage for various flow content elements and associated attributes. Elements and attributes demonstrated include:

·         Bold element
·         BreakPageBefore attribute
·         FontSize attribute
·         Italic element
·         LineBreak element
·         List element
·         ListItem element
·         Paragraph element
·         Run element
·         Section element
·         Span element
·         Variants attribute (superscript and subscript)
·         Underline element

<FlowDocument 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Paragraph FontSize="18">Flow Format Example</Paragraph>
 
    <Paragraph FontSize="18">More flow elements</Paragraph>
    <Paragraph FontSize="15">Inline, font type and weight, and a List</Paragraph>
 
    <List>
      <ListItem><Paragraph>ListItem 1</Paragraph></ListItem>
      <ListItem><Paragraph>ListItem 2</Paragraph></ListItem>
      <ListItem><Paragraph>ListItem 3</Paragraph></ListItem>
      <ListItem><Paragraph>ListItem 4</Paragraph></ListItem>
      <ListItem><Paragraph>ListItem 5</Paragraph></ListItem>
    </List>
 
    <Paragraph><Bold>Bolded</Bold></Paragraph>
    <Paragraph><Underline>Underlined</Underline></Paragraph>
    <Paragraph><Bold><Underline>Bolded and Underlined</Underline></Bold></Paragraph>
    <Paragraph><Italic>Italic</Italic></Paragraph>
 
    <Paragraph><Span>The Span element, no inherent rendering</Span></Paragraph>
    <Paragraph><Run>The Run element, no inherent rendering</Run></Paragraph>    
 
    <Paragraph FontSize="15">Subscript, Superscript</Paragraph>
 
    <Paragraph>
      <Run Typography.Variants="Superscript">This text is Superscripted.</Run> This text isn't.
    </Paragraph>
    <Paragraph>
      <Run Typography.Variants="Subscript">This text is Subscripted.</Run> This text isn't.
    </Paragraph>
    <Paragraph>
      If a font does not support a particular form (such as Superscript) a default font form will be displayed.
    </Paragraph>
 
    <Paragraph FontSize="15">Blocks, breaks, paragraph</Paragraph>
 
    <Section><Paragraph>A block section of text</Paragraph></Section>
    <Section><Paragraph>Another block section of text</Paragraph></Section>
 
    <Paragraph><LineBreak/></Paragraph>
    <Section><Paragraph>... and another section, preceded by a LineBreak</Paragraph></Section>
 
    <Section BreakPageBefore="True"/>
    <Section><Paragraph>... and another section, preceded by a PageBreak</Paragraph></Section>
 
    <Paragraph>Finally, a paragraph. Note the break between this paragraph ...</Paragraph>
    <Paragraph TextIndent="25">... and this paragraph, and also the left indention.</Paragraph>
 
    <Paragraph><LineBreak/></Paragraph>
 
</FlowDocument>

3D Programming:
WPF uses DirectX as its rendering engine. The framework allows much more than only 2D programming. Before we start with a simple 3D example, you should know some basics:
3D model
A 3D model is an object that will be presented in your application. A model is defined by triangles. The triangles together build up a mesh. For each point, the coordinates X,Y and Z have to be defined.
Camera
A camera specifies how you look at the model/scene.
Light
As in normal life, we need light to see something. :) There are multiple types of light.
Example:
You can create the models in XAML or C#. There are some tools, which are able to export the model (created in a designer) into XAML. For this example, I used only XAML.
First we define the points (attribute Positions) and then the “connection” between them (attribute TriangleIndicies). There are two ways for defining a point:
-1, 1, 0 or -1 1 0. The order is following: X, Y and then Z.

    <viewport3d name="Cube">
       
        <viewport3d.camera>
            <perspectivecamera position="2.1 4.5 6" lookdirection="-2 -5 -6" fieldofview="70">
            </perspectivecamera>
        </viewport3d.camera>
        <viewport3d.children>
            <modelvisual3d>
                <modelvisual3d.content>
                   
                    <directionallight color="#FFFFFF" direction="1,-2,-5">
                    </directionallight>
                </modelvisual3d.content>
            </modelvisual3d>
            <modelvisual3d>
                <modelvisual3d.content>
                    <geometrymodel3d>
                        <geometrymodel3d.geometry>
                            <meshgeometry3d triangleindices="0 1 2  2 3 0
                                             4 5 6  6 7 4
                                             8 9 10 10 11 8
                                             12 13 14  14 15 12
                                             16 17 18  18 19 16
                                             20 21 22  22 23 20" positions="-1,-1,-1  1,-1,-1  1,-1, 1 
                                       -1,-1, 1  -1,-1, 1  1,-1, 1  
                                       1, 1, 1  -1, 1, 1  1,-1, 1
                                       1,-1,-1  1, 1,-1  1, 1, 1
                                       1, 1, 1  1, 1,-1  -1, 1,-1 
                                       -1, 1, 1  -1,-1, 1  -1, 1, 1 
                                       -1, 1,-1  -1,-1,-1  -1,-1,-1 
                                        -1, 1,-1  1, 1,-1  1,-1,-1">
                            </meshgeometry3d>
                        </geometrymodel3d.geometry>
                        <geometrymodel3d.material>
                            <diffusematerial>
                                <diffusematerial.brush>
                                    <solidcolorbrush color="LightBlue">
                                    </solidcolorbrush>
                                </diffusematerial.brush>
                            </diffusematerial>
                        </geometrymodel3d.material>
                        <geometrymodel3d.transform>
                            <rotatetransform3d>
                               
                                <rotatetransform3d.rotation>
                                    <axisanglerotation3d x:name="rotation" axis="1,1,0" angle="0">
                                    </axisanglerotation3d>
                                </rotatetransform3d.rotation>
                            </rotatetransform3d>
                        </geometrymodel3d.transform>
                    </geometrymodel3d>
                </modelvisual3d.content>
            </modelvisual3d>
        </viewport3d.children>
        <viewport3d.triggers>
           
            <eventtrigger routedevent="Viewport3D.Loaded">
                <beginstoryboard>
                    <storyboard>
                       
                        <doubleanimation storyboard.targetname="rotation" storyboard.targetproperty="Angle" from="0" to="360" duration="0:0:4" autoreverse="False" repeatbehavior="Forever">
                        </doubleanimation>
                    </storyboard>
                </beginstoryboard>
            </eventtrigger>
        </viewport3d.triggers>
    </viewport3d>


Highly Composable:
Controls in WPF are extremely composable. You can define almost any type of controls as content of another. Although these flexibility sounds horrible to designers, its a very powerful feature if you use it appropriate. Put an image into a button to create an image button, or put a list of videos into a combobox to choose a video file.
    Orientation="Horizontal">
        Source="speaker.png" Stretch="Uniform"/>
        Text="Play Sound" />
    
Animations and time lines:
Animations are very cool, but they can cause a high CPU load. One reason could be a missing hardware acceleration due to a old graphics adapter or a software rendering constraint. Another reason could be the the high frame rate of animations that is set to 60 fps by default.
You can easily lower the framerate for all animations by overriding the DesiredFrameRate property of the timeline. Just add the following code to your project and play around with the setting to find a good tradeoff between performance and aesthetic.
 
Timeline.DesiredFrameRateProperty.OverrideMetadata (typeof(Timeline),
   new FrameworkPropertyMetadata { DefaultValue = 30 });
 

 Or you can set the framerate individually for each animation in XAML, using the following code:
 
TargetProperty="Opacity" Duration="0:0:0.5" 
                 From="1.0" To="0.5" Timeline.DesiredFrameRate="30" />
 
 

Powerful Binding:
WPF provides a simple and powerful way to auto-update data between the business model and the user interface. This mechanism is called DataBinding. Everytime when the data of your business model changes, it automatically reflects the updates to the user interface and vice versa. This is the preferred method in WPF to bring data to the user interface.
Databinding can be unidirectional (source -> target or target <- class="apple-converted-space" source="" span=""> or bidirectional (source <-> target).
The source of a databinding can be a normal .NET property or a DependencyProperty. The target property of the bindingmust be a DependencyProperty.
To make the databinding properly work, both sides of a binding must provide a change notification that tells the binding when to update the target value. On normal .NET properties this is done by raising the PropertyChanged event of theINotifyPropertyChanged interface. On DependencyProperties it is done by the PropertyChanged callback of the property metadata
Databinding is typically done in XAML by using the {Binding} markup extension. The following example shows a simple binding between the text of a TextBox and a Label that reflects the typed value:
    x:Name="txtInput" />
    
                     UpdateSourceTrigger=PropertyChanged}" />

Resolution independent:
All measures in WPF are logical units - not pixels. A logical unit is a 1/96 of an inch. If you increase the resolution of your screen, the user interface stays the same size - it just gets crispier. Since WPF builds on a vector based rendering engine it's incredibly easy to build scaleable user interfaces.
Highly Customizable:
Because of the strict separation of appearance and behavior you can easily change the look of a control. The concept ofstyles let you skin controls almost like CSS in HTML. Templates let you replace the entire appearance of a control.




No comments:

Post a Comment