WPF - Overview and Sample Code Snippets in C#


WPF - Overview and Sample Code Snippets in C#

A Fast-Track Overview of WPF



What is WPF?

- Windows Presentation Foundation.
- Next generation UI framework.
- Rich UIs, 2D, 3D graphics and multimedia in a single framework.

Why WPF?

- Prior to WPF, Windows developer would have to learn several independent technologies with number of inconsistencies if he wanted to use 2D, 3D,video, speech etc.
- WPF covers all these areas with a consistent programming model.

Features of WPF?

- Hardware acceleration (Direct 3D)
- Declarative UI with XAML
- Multimedia Support
- 3D programming and Animations
- Resolution independent
- Vector Based Rendering

Separation of Appearance and Behavior?

- Appearance is handled by XAML (Extensible Application Markup Language)
- Behavior is handled by C# code behind.
- Both ate integrated with the databinding, events and commands.

Benefits of this separation?

- Appearance and behavior are loosely coupled.
- Designer and developers can work separately on their modules.
- Graphic tools can easily work on the XML Files instead of complex parse codes.

Rich Composition of controls?

- WPF controls are extremely composible
- Once control can be used as content of other control easily.
- Like placing an image to normal button can form an image button.
- Place a list of videos on a combobox is also simple.

What is XAML?

- It stands for Extensible Application markup language.
- Its based on XML.
- It is used to create User interfaces for WPF, Silverlight

Advantages of XAML?

- All we can do in XAML, we can do in code. Hence XAML is not compulsory.
- We can use WPF without XAML. But using XAML has some advantages like;
-- Its code is short and easy to understand.
-- It separates the UI Appearance and logic code.
-- Designer and developer can work independently.

Comparisons in XAML and corresponding Code?

Suppose we build a StackPanel with a text box and a button.

- XAML


<StackPanel>
<TextBox Margin="20">
Welcome to the world of XAML
</TextBox>
<Button Margin="10" HorizontalAlignment="Right">
OK
</Button>
</StackPanel>

- C#



// Create the MyPanel
StackPanel stackPanel = new StackPanel();
This.Content = stackPanel;

// Create the textbox
TextBox textBox = new TextBox();
textBox.Margin = new Thickness(20);
textBox.Text = “Welcome to the world of XAML";
stackPanel.Children.Add(textBlock);

// Create the button
Button button = new Button();
button.Margin = new Thickness(10);
button..Text = “OK";
stackPanel.Children.Add(button);




- Its obvious from above comparisons that which approach is easy.

What are Markup Extensions in XAML?

- These are dynamic placeholders for the attributes of XAML.
- They resolve the values of properties at run-time.
- These are surrounded by curly braces {}.
- WPF has some built-in markup extensions but we can create our own.
- For this we need to derive them from MarkupExtension.


Syntax of Markup Extension ?



<TextBox x:Name="textBox"/>
<label Content="{Binding Text, ElementName=textBox}"/>




The first part in the brace is “name of extension"
The preceding identifiers are names parameters e.g. property=value

In above example, when a text is entered in the text box at runtime, the label content is auto updated at run-time.

What are built-in markup extensions?

- Binding
-- Binds 2 properties together
- TemplateBinding
-- Binds a control template property with control dependency property.
- StaticResource
-- One time lookup
- DynamicResource
-- Auto updating lookup
- x:Static
-- Resolve static property value
- x:null
-- Returns null

What are namespaces for XAML?

- We need to add 2 namespaces in the beginning of XAML
-- presentation ..
http://schemas.microsoft.com/winfx/2006/xaml/presentation
Its mapped to all wpf controls in System.Windows.Controls
-- xaml ..
http://schemas.microsoft.com/winfx/2006/xaml
Its mapped to System.Windows.Markup for XAML keywords
- Syntax:



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



Which attribute maps the XAML namespace with CLR namespace?

- XmlnlDefinition.

What is Logical Tree ?

- Elements of WPF UI are hierarchically related. Its Logical-Tree.
- It describes the relations between the elements and user interface.

What is Visual Tree?

- Template of one element consists of multiple visual elements. Its Visual-Tree.
- It includes all the Logical trees and visual elements of all element.

Why do we need two different kind of Trees?

- A WPF control consists of multiple controls.
- Like, a button, it has visual children like; border, rectangle, content presenter.
- When WPF renders button control, it iterates through the visual tree and renders all the visual child of it.
- But sometimes, we don't want to work with some elements like; border, rectangle. Then comes Logical-tree in picture.

What are the factors, a Logical tree responsible for?

- Inherit DependencyProperty values.
- Resolve DynamicResources references.
- Looking up element names for binding.
- Forwarding RouteEvents.

What are the factors, a Visual tree responsible for?

- Render visual elements
- propagate layout and RenderTransforms
- Propagate IsEnabled property
- Does Hit-testing
- Find Relative Sources (FindAncestor)


What is Hit Testing?

- This method to determine whether a point value falls in a content area.
- We can find whether a mouse click falls within the boundary of a circle.
- Illustration for HitTest region…


+--------------------------+
|..........................|
|..........................o----> Rectangle Boundary
|....+-----------------+...|
|....|.................|...|
|....|.............o------------> Visual Object (Target)
|....|.................|...|
|....o--------------------------> Visual Object Boundary
|....|.................|...|
|....|...........o--------------> Hit Test Successful
|....+-----------------+...|
|..........................|
|...................o-----------> Hit Test failed
+--------------------------+


Draw a Logical Tree ?

Windows
|
+------ Grid
...........|
...........+------ LabelButton
...........|
...........+------ Button


Draw a Visual Tree ?

Windows
|
+------ [Border]
|
+------ Grid
...........|
...........+------ LabelButton
...........|..........|
...........|..........+------ [Border]
...........|..........|
...........|..........+------ [TextBox]
...........+------ Button
......................|
......................+------ [Border]
......................|
......................+------ [TextBox]
......................|
......................+------ [ContentHolder]


- Nodes with […] are part of Visual tree


What is the use

Write the code to support Mouse event handler to capture Hit Test ?



// Respond to the left mouse button down event by initiating the hit test.
private void OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
// Retrieve the coordinate of the mouse position
Point pt = e.GetPosition((UIElement)sender);

// Perform the hit test against a given portion of the visual object tree
HitTestResult result = VisualTreeHelper.HitTest(myCanvas, pt);

if (result != null)
{
// Action-perform
}
}



Write code to find Ancestor in a Visual tree ?

- Steps are:

1. Get the reference of dependency object (as a starting node)
2. Gets its parent node and assign back to target.
3. While (new target is not null) then (repeat from step 1)
4. return the target object to caller

- This is achieved by the VisualTreehelper class.
- GetParent(DependencyObject) is used

sample:



public static class VisTreeHlpr
{
public static T FindAncestor(DependencyObject dobj) where T : class
{
DependencyObject target = dobj;
do
{
target = VisualTreeHelper.GetParent(target);
}
while (target != null && !(target is T));
return target as T;
}

}



- Calling the helper method (in this example it a call from HTML script)



var grid = VisualTreeHelperExtensions.FindAncestor(this);




What are Routing Events ?

- They navigate up or down the visual tree according to RoutingStrategy.
- They normally appear in pair. Like, tunneling even PreviousMouseDown is called then bubbling event MouseDown is called.

What is Routing Strategy ?

- A Routing Strategy can be Bubble, Tunnel, or Direct.
- Tunneling:
1. Raised on root element in the visual tree.
2. Navigates down to the tree until it reaches to source element or stopped by making event as handled.
3. It appears before Bubbling event.
- Bubbling:
4. Raised on the source element.
5. Navigates up to the tree until it reaches to root element or stopped by making event as handled.
6. It appears after Tunneling event.
- Direct:
7. Raised on the source element
8. Must be handled on the source element itself.
9. This behavior is same as .Net event behavior.


How to create a Custom Routed handler ?

- Steps are :
1. Register the Route Event.
2. create a .Net wrapper for the event
3. raise the routed event.



// Register the routed event (typical syntax)
public static readonly RoutedEvent SelectedEvent =
EventManager.RegisterRoutedEvent( "Selected", RoutingStrategy.Bubble,
typeof(RoutedEventHandler), typeof(MyCustomControl));

// .Net Wrapper
public event RoutedEventHandler Selected
{
add { AddHandler(SelectedEvent, value); }
remove { RemoveHandler(SelectedEvent, value); }
}

// Raise the routed event "selected"
RaiseEvent(new RoutedEventArgs(MyCustomControl.SelectedEvent));




What is the relation between WPF and Direct3D ?

- Both are 2 different API's but WPF internally uses Direct3X.
- WPF
-- Lets developers explore their creativity in .Net application flavor
-- Lets us move into 3D/light shades/effects with minimal extra efforts.
-- It uses DirectX as its rendering engine.
-- WPF uses XAML to create the data structure that DirectX needs.
-- Once it's internally supplied to DirectX APIs, DirectX does all heavy tasks, like performing complex mathematical calculations, rendering thousands of objects in fraction of second.
-- WPF gives us more productivity, power, ease then any other technology we used in past.
-- Behind the scene, the contents in WPF application – whether 2D, 3D, graphics, text is converted first into 3D triangles, textures and other Direct3D objects and then the hardware renders them. That means the fine rendering work is off-loaded to GPS (Graphics processing unit) of CPU.
-- WPF has core pieces implemented in unmanaged code & exposes some lowlevel unmanaged APIs to write own imaging CODECs or bitmap effects.
- DirectX
-- Its low level interface to the graphics hardware of underlying system.
-- intended to give access to underlying H/W & perform fast 3D animation.
-- for people, make 3D applications to provide a fast and rich 3D support.
-- DirectX can be used instead of WPF but it needs more code work like; finding the details of underlying H/w, H/w rendering model, how to optimize the rendering. Instead WPF does all these for us.
-- So the, DirectX is 2D/3D with hardware acceleration.


DirectX or WPF ?

- Using DirectX over WPF will be a potentially costly development cost and the large part of this cost would go to testing DirectX application into multiple testing scenarios.
- Whereas WPF takes over all these overheads and does it for the developer, hence reducing the overall application costing.
- Another reason that why WPF should be used, is a ton of WPF functions have already being developed and tested by Microsoft and the developers have to just leverage the available features with a minimal testing efforts.

What is MVVM pattern?

- It's a flexible and powerful databinding framework for WPF
- It stands for Model-View-ViewModel pattern

Why the idea of MVVM introduced?

- In conventional WinForms prog has many events which are defined in the code-behind for its UI controls. Of course it is fastest and simple way for binding UI and its functionality. But it has some advantages…
-- The Presentation & logic are tightly coupled
-- Replace a control in view needs many code changes.
-- Complex UI testing is required to test user interface logic.
- WPF brings with an idea of MVVP to give many benefits over conv. prog.
-- Model: To explore and contain the data
-- ViewModel: To collect & prepare data that view can easily consume.
-- View: XAML based layer that is used to design the User Interface.

What is the Development Work-flow of WPF?

- It has many steps to decide development workflow of specific WPF application
-- Obtain requirements
-- (done by requirement engineer)
-- Requirements are collected to decide destination of application.
-- Stakeholders and users are interviewed to gather requirements
-- Then tasks are prioritized according to Risk/importance
-- Create and validate UI prototype
-- (done by Interaction designer)
-- UI's are created to define the various usecases.
-- Prior to go with discussion, always better to sketch paper UI.
-- Popular techniques may be…
.. Paper prototypes
.. Wireframes
.. Sketch flow
.. Realistic UI prototypes
-- A real users should be considered to address real design problem & complexities. This can be done as follows…
.. Walk-through end users with paper-layouts/wireframes
.. Demonstrate realistic UI-POCs to user to get their ideas.
-- Implementation business logic and create Raw-UI
-- (done by Software Developer)
-- Integrate Graphical Design
-- (done by Graphical engineer)
-- Test Software
-- (done by Software Tester)

What is difference in User Controls and Custom Controls in context of WPF?

- User Control:
-- composition of existing UI controls.
-- It has a XMAL file and a code behind file.
-- It is derived from UserControl class.
-- It cannot be templated.
-- Example would be…


- Custom Control:
-- Extension of existing control with additional featured.
-- It has default Themes/Generics.xaml file and a code behind file.
-- It can be templated.
-- Example would be…

-- Its an extension of a text box with value up/down features.
-- Up/Down buttons defined in control and wiredup in OnApplyTemplate() to override the logic part of control.
-- The ControlTemplace can easily be exchanged with another controls.

What are the points that need to be considered before going with Custom Controls ?

- What problem should my control solve.
- Who will use this control and under which scenarios.
- Can we extend existing controls to achieve the requirements.
- Should it be possible to style or template my control.
- What is design-time support available.
- Is it going to be used in single or multiple projects?

What is Markup Extension ?

- Extends the expressibility of XMAL
- It can evaluate string-expression value at run-time
- Example



<Button xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Background="{x:Null}"
Height="{x:Static SystemParameters.IconHeight}"
Content="{Binding Path=Height, RelativeSource={RelativeSource Self}}"
/>




This is just similar to following example…



<Button xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Button.Background>
<x:Null/>
</Button.Background>
<Button.Height>
<x:Static Member="SystemParameters.IconHeight"/>
</Button.Height>
<Button.Content>
<Binding Path="Height">
<Binding.RelativeSource>
<RelativeSource Mode="Self"/>
</Binding.RelativeSource>
</Binding>
</Button.Content>
</Button>




- Description
-- First identifier in each curly braces is name of Markup element class.
In which x prefix is used to locate the corresponding class in System.Window.Markup namespace.
Like; {x:null} and {x:Static …….}
--


Sample # - Sample WPF application for “Hello World"

- Steps to follow:
- Visual Studio 2008
- "File"
- "New"
- "Project..."
- "WPF Application" as project type
- Choose a folder for project and give it a name
- Click "OK"
- Open the Window1.xaml file and drag a Button and text box on the container
- Double click Button and add following code in that…


private void button1_Click(object sender, RoutedEventArgs e)
{
textBox1.Text = "Hello World!";
}


- F5 to run application.

I hope, I am able to cover import topics about WPF in this article.



Regards!


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: