Wpf assembly & namespace

Document Sample
Wpf assembly & namespace Powered By Docstoc
					WPF

Introduction To WPF
WPF stands for Windows Presentation Foundation (WPF) is a next-generation presentation system for building
Windows client applications with visually stunning user experiences. With WPF, you can create a wide range of both
standalone and browser-hosted applications.

The core of WPF is a resolution-independent and vector-based rendering engine that is built to take advantage of
modern graphics hardware. WPF extends the core with a comprehensive set of application-development features
that include Extensible Application Markup Language (XAML), controls, data binding, layout, 2-D and 3-D graphics,
animation, styles, templates, documents, media, text, and typography. WPF is included in the Microsoft .NET
Framework, so you can build applications that incorporate other elements of the .NET Framework class library.

WPF Advantages:

1. Broad Integration: Prior to WPF, it was very difficult to use 3D, Video, Speech, and rich document viewing in
addition to normal 2D Graphics and controls would have to learn several independent technologies. WPF covers all
these with consisting programming model as well as tight integration when each type of media gets composited and
rendered.

2. Resolution Independence: WPF applications are device independent i.e., smart client applications. Like normal
applications it won’t get decrease the size as the resolution gets increase. This is possible because WPF emphasis on
vector graphics.

3. Hardware Acceleration: WPF is built on top of Direct 3D, content in a WPF application whether 2D or 3D, Graphics
or text is converted to 3D triangles, textures and other Direct 3D objects and then rendered by hardware. WPF
applications can get the benefit of hardware acceleration for smoother graphics and all round better performance.

4. Declerative Programming: WPF takes the declarative programming to the next level with the introduction of
Extensible Application Markup Language(XAML), pronounced as “Zammel”.
XAML is like HTML in web used for creating the interface, resulting graphical designers are empowered to contribute
directly to the look and feel of applications.

5. Rich Composition and Customization: WPF controls are extremely compostable.
Eg: we can create combo box with animated buttons.

Applications of WPF
WPF has comprehensive features for creating user experiences with rich content. To package this content and
deliver it to users as "applications," WPF provides types and services that are collectively known as the application
model. The application model supports the development of both standalone and browser-hosted applications.

Standalone Applications
  For standalone applications, you can use the Window class to create windows and dialog boxes that are accessed
from menu bars and tool bars.

Additionally, you can use the following WPF dialog boxes: MessageBox, OpenFileDialog, SaveFileDialog, and
PrintDialog.

Browser-Hosted Applications
For browser-hosted applications, known as XAML browser applications (XBAPs), you can create pages (Page) and
page functions (PageFunction<T>) that you can navigate between using hyperlinks (Hyperlink classes).
For Browser-Hosted Application we will discuss later.
Core WPF Assemblies and Namespaces
Like any .NET technology, WPF is represented by several assemblies. The Visual Studio WPF project
templates automatically set references to the necessary assemblies. However, if you build WPF apps using
other IDEs or via msbuild.exe, you will need to set references manually. The following key libraries are
managed .NET assemblies:


WPF Assembly

                                Meaning in Life

                                Defines the base infrastructure of WPF, including dependency
                                properties support.
WindowsBase.dll
                                While this assembly contains types used within the WPF
                                framework, the majority of these types can be used within other
                                .NET applications.

PresentationCore.dll            This assembly defines numerous types that constitute the
                                foundation of the WPF GUI layer.

                                This assembly—the ‘meatiest’ of the three—defines the WPF
                                controls types, animation and multimedia support, data binding
PresentationFoundation.dll      support, and other WPF services.

                                For all practical purposes, this is the assembly you will spend
                                most of your time working with directly.

Although these assemblies provide hundreds of types within numerous namespaces, consider this partial list
of WPF namespaces:
   •    You will encounter other namespaces during the remainder of this class.
   •    Again, consult the .NET Framework SDK documentation for full details.




WPF Namespace                Meaning in Life

System.Windows               Here you will find core types such as Application and Window that
                             are required by any WPF desktop project.

System.Windows.Controls      Here you will find all of the expected WPF widgets, including types
                             to build menu systems, tool tips, and numerous layout managers.

System.Windows.Markup        This namespace defines a number of types that allow XAML
                             markup and the equivalent binary format, BAML, to be parsed.

System.Windows.Media         Within these namespaces you will find types to work with
                             animations, 3D rendering, text rendering, and other multimedia
                             primitives.

System.Windows.Navigation This namespace provides types to account for the navigation logic
                          employed by XAML browser applications / desktop navigation apps.
System.Windows.Shapes         This namespace defines basic geometric shapes (Rectangle, Polygon,
                              etc.) used by various aspects of the WPF framework.


These three core WPF assemblies work in conjunction with two lower-level libraries, milcor.dll and
WindowsCodecs.dll. Most WPF developers will never need to work directly with these lower-level libraries.
In a nutshell, these two libraries provide a mapping layer between the managed WPF libraries and the
underlying OS kernel / D


Arranging Content with Panels
When you are building a GUI using WPF, you are required to make use of panel types. Recall that a
ContentControl can only have one item assigned to its Content property.

If you were to add a UI widget directly to a ContentControl, it will be positioned in the dead center. Consider
the following simple window, which sets a Rectangle as content (note the lack of any panel type):


<Window x:Class = "FunWithPanels.Window1"
 xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
 Title = "The only content I have..." Height = "299" Width = "348">

<Rectangle Fill = "Black" Height = "50" Width = "100"/>

</Window>

Multiple UI elements must first be arranged in one of the provided panel types. Here are the most frequently
used panel types, all of which are defined in the System.Windows.Controls namespace of
PresentationFoundation.dll.




WPF Panel Type

                      Meaning in Life

                      Provides a ‘classic’ mode of content placement. Items stay exactly where
Canvas                you put them at design time as items make use of absolute positions.


                      Locks content to a specified side of the panel (Top, Bottom, Left, or
DockPanel             Right).

                      Arranges content within a series of cells, based on rows and columns,
Grid                  maintained within a tabular grid.


                      Stacks content in a vertical or horizontal manner as dictated by the
StackPanel            Orientation property.
                      Positions content from left to right, breaking the content to the next line
WrapPanel             at the edge of the containing box.

                      Subsequent ordering happens sequentially from top to bottom or from
                      right to left, depending on the value of the Orientation property.


Be aware that each one of these panel types can be configured in numerous ways. Your lab time will illustrate
a number of configuration settings. However, you will most certainly want to look up panels of interest in the
.NET Framework SDK documentation for full details.




Working with DockPanel
The DockPanel type, as the name implies, allows you to dock items, including other panels, to a fixed
position. Again, Top, Left, Bottom, Right attached properties are used by the sub-elements. Given that the
following Button type has not specified any DockPanel.Dock value, it will therefore be stretched within the
remaining space.


<DockPanel>
<!-- Dock items to the panel -->
<Label DockPanel.Dock = "Top" Name = "lblInstruction"
     FontSize = "15">Enter Car Information</Label>
<Label DockPanel.Dock = "Left" Name = "lblMake">Make</Label>
<Label DockPanel.Dock = "Right" Name = "lblColor">Color</Label>
<Label DockPanel.Dock = "Bottom" Name = "lblPetName">
     Pet Name</Label>
<Button Name = "btnOK">OK</Button>
</DockPanel>




Working with StackPanel
The StackPanel control arranges content into a single line that can be oriented horizontally or vertically (the
default), based on the value assigned to the Orientation property. It is very useful to ensure that part of the
screen real estate is stacked in a given order when the user resizes. Typically, StackPanels are embedded
within another larger container such as the Grid.


<StackPanel Background = "LightSteelBlue">
<Label Name = "lblInstruction"
    FontSize = "15">Enter Car Information</Label>
<Label Name = "lblMake">Make</Label>
<TextBox Name = "txtMake"/>
<Label Name = "lblColor">Color</Label>
<TextBox Name = "txtColor"/>
<Label Name = "lblPetName">Pet Name</Label>
<TextBox Name = "txtPetName"/>
<Button Name = "btnOK">OK</Button>
</StackPanel>
Working with the Grid
Of all the panels provided with the WPF APIs, Grid is far and away the most flexible. Like an HTML table,
the Grid can be carved up into a set of cells, each one of which contains content.

When defining a Grid, you perform three steps:
 •    Define each column in the grid.
 •    Define each row in the grid.
 •     Assign content to each cell of the grid using attached-property syntax.

Here is a grid consisting of four cells. For display purposes, the ShowGridLines property has been set to
true.


<Grid ShowGridLines = "True" Background = "AliceBlue">
<!-- Define the rows / columns. -->
<Grid.ColumnDefinitions>
 <ColumnDefinition/>
 <ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
 <RowDefinition/>
 <RowDefinition/>
</Grid.RowDefinitions>




Establishing WPF-specific XML Namespaces

The root element of a XAML document typically defines two XML namespaces that map to core WPF
namespaces and XAML specific tokens.
 •     http://schemas.microsoft.com/winfx/2006/xaml/presentation maps a number of WPF
      namespaces for use by the current *.xaml file:
     •      System.Windows, System.Windows.Controls, System.Windows.Data, System.Windows.Ink,
           System.Windows.Media, System.Windows.Navigation, etc.
 •     http://schemas.microsoft.com/winfx/2006/xaml is used to include XAML specific tokens, as
      well as a subset of types within the System.Windows.Markup namespace.

Here would be a <Window> that defines these two XML namespaces. Given the cascading nature of XML,
all sub-elements of the <Window> have access to the same information.



<Window
xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml">
</Window>



The first xmlns attribute is the primary namespace as it has not been qualified with a namespace prefix.
Notice that the second xmlns attribute as been given the ‘x’ prefix. This is simply to avoid ambiguity with the
other namespace definitions. Like any XML prefix, the actual name is irrelevant. Thus, the following
<Window> definition is also permissible although more verbose.
<Window
xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:XamlSpecificStuff =
 "http://schemas.microsoft.com/winfx/2006/xaml">
</Window>


If you did use the ' XamlSpecificStuff' prefix, any XAML keyword in the defining scope would now need to
make use of this rather verbose tag. Consider the following <Application> root element, which illustrates the
simplicity of ‘x’ as a tag prefix for the XAML-centric namespace.

<Application XamlSpecificStuff:Class="SimpleXamlApp.MyApp"
xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns: XamlSpecificStuff = "http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri = "MainWindow.xaml" Exit="AppExit">

<XamlSpecificStuff:Code>
<![CDATA[
private void AppExit(object sender, ExitEventArgs e)
{
  MessageBox.Show("App has exited");
}
]]>
</XamlSpecificStuff:Code>

</Application>

Beyond the two key XML namespaces, XAML makes it possible to define custom xmlns values that map to
custom assemblies. This can be helpful when your markup needs to refer to types defined in external libraries.
The clr-namespace token is used to do this very thing.

You will see why this can be quite useful over the course of this class. Here is a simple example that makes
the types in the System namespace of mscorlib.dll available within the current <Window>. If you are
mapping to a namespace in the current assembly, the assembly qualifier is optional as seen in the second
XML namespace listing.


<Window
xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:CorLib = "clr-namespace:System;assembly=mscorlib"
xmlns:MyTypes = "clr-namespace:SomeNamespaceInMyAssembly">
</Window>


Understanding the Role of XAML
Although XAML is a key aspect of WPF, few developers will need to author reams of XAML by hand
XAML, like any XML-based grammar, is verbose, tedious, and error prone. Numerous tools such as Visual
Studio and Expression Blend will generate XAML on your behalf as you make use of the tool itself.
Although it is true that WPF development tools will generate XAML in the background, it is important to
understand the basic syntax. This will allow you to tweak the generated XAML if the need should arise.

Also, XAML can be generated, loaded, parsed, and manipulated at runtime. To understand how to do so, a
working knowledge of XAML’s syntax is useful.

It is important to recall that XAML is a general-purpose markup language and is not limited to WPF. XAML
can also be found within the Windows Workflow Foundation API, where it is used to build custom activities
and workflows via markup. XAML is also used within Silverlight applications. XAML is also used by the
XML Paper Specification (XPS), a Microsoft technology for e-paper.

As detailed in your next lab, msbuild.exe uses XAML descriptions to generate intermediate code files used
during the compilation process. As a naming convention, these file have a ‘g’ infix (for generated). For
example, a XAML file named MyWindow.xaml will be used by msbuild.exe to generate a C# file named
MyWindow.g.cs or a VB file named MyWindow.g.vb. Within these generated files, you will find code-based
equivalents for various aspects of your XAML markup.

XAML files are also used to generate a compact binary form of the markup termed binary markup language
(BAML). By default, the BAML is embedded into your .NET assembly as a binary resource. At runtime, the
BAML is parsed to hydrate the state of your WPF objects (windows, applications, controls, and so on).

Because of BAML, you are seldom required to ship XAML files along with your compiled WPF application.
Unless you are dynamically loading external XAML files into memory, XAML files can be regarded as little
more than input to msbuild.exe.


Nesting Panels within Panels
When you are building a Window, you will typically find that the Content property is a panel that contains
additional panels. This allows you to carve out chunks of screen space, where each chunk behaves uniquely.
You may wish to have part of your UI resize content when maximized, where another part of your UI should
remain fixed.

Consider the following DockPanel. The DockPanel has set the LastChildFill property to true, which is the
default. In this way, the TextBlock will take up the remainder of the UI, regardless of the window’s size. The
DockPanel defines a <Menu> (docked to the top), <StatusBar> (docked to the bottom), and a
<StackPanel> docked to the left. The <StackPanel> contains a set of UI elements.


<!-- This panel establishes the content for the window. -->
<DockPanel LastChildFill="True">

<!-- Put a Menu and toolbar at the top. -->
<Menu DockPanel.Dock = "Top" HorizontalAlignment = "Left"
       Background = "White">
<MenuItem Header = "_File">
  <Separator/>
  <MenuItem Header = "_Exit" />
</MenuItem>
</Menu>

<!-- Put a StatusBar at the bottom. -->
<StatusBar Name = "statBar"
DockPanel.Dock = "Bottom"
VerticalAlignment = "Bottom"
Background = "Beige" >
<StatusBarItem>
 <TextBlock>Ready</TextBlock>
</StatusBarItem>
</StatusBar>

<!-- Put a StackPanel on the left. -->
<StackPanel Background = "LightSteelBlue" Orientation = "Vertical"
      DockPanel.Dock = "Left">
<Label Name = "lblInstruction"
      FontSize = "15">Enter Car Information</Label>
<Label Name = "lblMake">Make</Label>
<TextBox Name = "txtMake"/>
<Label Name = "lblColor">Color</Label>
<TextBox Name = "txtColor"/>
<Label Name = "lblPetName">Pet Name</Label>
<TextBox Name = "txtPetName"/>
<Button Name = "btnOK">OK</Button>
</StackPanel>

<!-- The final area will be a block of text wrapped in a border. -->
<Border BorderThickness = "3" BorderBrush = "DarkRed">
<TextBlock Background = "LemonChiffon" FontSize = "20">
      Desktop markup? I like it!</TextBlock>
</Border>
</DockPanel>


Separation of Concerns Using Code Files
Few WPF applications will take the 100% code or 100% XAML approach as you have seen thus far. In
reality, a ‘middle of the road’ approach is recommended.

Similar to an ASP.NET web application, WPF allows you to have a C# (or VB) file that works in conjunction
with a related XAML file. The XAML file is only concerned with UI descriptions defined via markup. The
code file is concerned with programming logic.

Elements defined in XAML can be accessed in the code file and vice versa if required. To do so, you should
assign a Name property to the XAML element.

Here is the simple WPF application yet again, this time making use of code files. As a naming convention,
code files have -xaml- embedded within the file name. However, this is not required. Recall from your
previous lab that the auto-generated *.g.cs / *.g.vb file completes your partial class definition. The
InitializeComponent() method is defined within an auto-generated *.g.cs / *.g.vb file.




XAML-specific Elements and Attributes
Strictly speaking, XML-based grammars do not support true keywords. However, XML parsers can be
programmed to look for special tokens that will be treated in a special, customized manner. The same is true
for XAML as it defines a number of tokens that can be regarded as ‘keywords’ in a general sense. Many of
these are used to control how the XAML markup is processed at compile time via msbuild.exe.

Because these XAML-specific tokens are part of the XAML namespace, many of them must take an x:
prefix (x:Name, x:Code, x:Class, and so forth). As you will see, as a convenience, some tokens such as Name
do not require an x: prefix.
XAML Keyword

                            Meaning in Life

Array                       Used to represent a .NET array type in XAML.


                            Allows you to define the visibility of the class type (internal or public) denoted by the Class
ClassModifier               keyword.


DynamicResource             Allows you to make reference to a WPF resource that should be monitored for changes.



                            Allows you to define the visibility of a type member (internal, public, private, protected)
FieldModifier               for any named sub-element of the root (e.g., a <Button> within a <Window> element).



Key                         Allows you to establish a key value for a XAML item that will be placed into a resource
                            dictionary.


Name                        This allows you to specify the generated C# name of a given XAML element.



Null                        Represents a null reference.


Static                      Allows you to make reference to a static member
                            of a type.

StaticResource              Allows you to make reference to a WPF resource
                            that should not be monitored for changes.

                            This is the XAML equivalent of the C# typeof
Type                        operator / VB GetType operator. It will yield a
                            System.Type based on the supplied name.

As you have seen earlier in this chapter, the x:Class and x:Code tokens are XAML tokens. A Window or
Application can specify an x:Class attribute in its opening definition and is used to define the name of the
class type in the code files. The <x:Code> XAML element can be used to embed code within a XAML file.
Here is a <Window> element that defines the x:Class attribute:


<!-- The x:Class attribute will be used by msbuild.exe to
   Define a C# or VB class type to represent the
   code of this XAML. -->
<Window x:Class = "MyWPFApp.MainWindow"
  xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml">
</Window>
Triggers
A trigger sets properties or starts actions, such as an animation, when a property value changes or when an event is
raised. Style, ControlTemplate, and DataTemplate all have a Triggers property that can contain a set of triggers.
There are various types of triggers.

Property Triggers

A Trigger that sets property values or starts actions based on the value of a property is called a property trigger.

To demonstrate how to use property triggers, you can make each ListBoxItem partially transparent unless it is
selected. The following style sets the Opacity value of a ListBoxItem to 0.5. When the IsSelected property is true,
however, the Opacity is set to 1.0:

<Style TargetType="ListBoxItem">
  <Setter Property="Opacity" Value="0.5" />
  <Setter Property="MaxHeight" Value="75" />
  <Style.Triggers>
    <Trigger Property="IsSelected" Value="True">
      <Setter Property="Opacity" Value="1.0" />
    </Trigger>
...
  </Style.Triggers>
</Style>

This example uses a Trigger to set a property value, but note that the Trigger class also has the EnterActions and
ExitActions properties that enable a trigger to perform actions.



EventTriggers and Storyboards

Another type of trigger is the EventTrigger, which starts a set of actions based on the occurrence of an event. For
example, the following EventTrigger objects specify that when the mouse pointer enters the ListBoxItem, the
MaxHeight property animates to a value of 90 over a 0.2 second period. When the mouse moves away from the
item, the property returns to the original value over a period of 1 second. Note how it is not necessary to specify a
To value for the MouseLeave animation. This is because the animation is able to keep track of the original value.

    <EventTrigger RoutedEvent="Mouse.MouseEnter">
     <EventTrigger.Actions>
      <BeginStoryboard>
       <Storyboard>
        <DoubleAnimation
         Duration="0:0:0.2"
         Storyboard.TargetProperty="MaxHeight"
         To="90" />
       </Storyboard>
      </BeginStoryboard>
     </EventTrigger.Actions>
    </EventTrigger>
    <EventTrigger RoutedEvent="Mouse.MouseLeave">
     <EventTrigger.Actions>
      <BeginStoryboard>
       <Storyboard>
        <DoubleAnimation
         Duration="0:0:1"
         Storyboard.TargetProperty="MaxHeight" />
       </Storyboard>
      </BeginStoryboard>
     </EventTrigger.Actions>
    </EventTrigger>


MultiTriggers, DataTriggers, and MultiDataTriggers

In addition to Trigger and EventTrigger, there are other types of triggers. MultiTrigger allows you to set property
values based on multiple conditions. You use DataTrigger and MultiDataTrigger when the property of your condition
is data-bound.

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:30
posted:11/27/2012
language:English
pages:11