Wednesday, February 29, 2012

Windows Phone - Template (13)

Hello

Two types of templates :

  • DataTemplate - Render objects that have no visual representation
  • ControlTemplate - Customize visual appearance of controls


ContentControl , ContentTemplate and  DataTemplate
DataTemplate - Render objects that have no visual representation
ContentTemplate is the way to display Content.

Sample source
Templates_NK.zip

We have seen before (blog) how to set content for a button (ContentControl). Now i will use ContenetTemplate which is a property of ContentControl type DataTemplate.
Content is set to an object type CUser and it is the button DataContext i.e. Binding source. Given a source there is no need to define it for the two TextBlocks and only Path is left to be defined. for Binding.
The Button content is displayed by two TextBlocks as defined in ContentTemplate


Note that Path may be omitted from the Binding i.e


Run the application and click the "Data Template" button to produce :



ControlTemplate
ControlTemplate - customize visual appearance of controls

Every Control has a property name Template which is type ControlTemplate.
Template is common as part of Style.
Note that ControlTemplate changes the appearance of the control but not it's functionality.

Source sample
Templates_NK.zip

ControlTemplate.xaml

A button with ControlTemplate which includes Border andTextBlock



A button with ControlTemplate which includes Border andTextBlock using TemplateBinding
which means a binding between the ControlTemplate property and the templated control property. i.e. the boder BorderBrush property is binded to the Control BorderBrush, same goes for BorderThickness
Note that i used once TemplateBinding and once Binding with RelativeSource. However, they are equivalence.




Same as the first button but using style





Based on previous button but two changes :

  • Add corner to the Border
  • Add ContentPresenter and bind it to the Control Content so "Click Me" will appear. This solve the problem that the Content "Click Me" was not shown


Now i want to show the use of ControlTemplate and Style as resources so we can reuse them.

Three resources are defined :

  • templateButtonComplete - ControlTemplate for button with Border which defines BorderBrush,BorderThickness and CornerRadius and ContenetPresenter which is binded to it's control content
  • templateButtonBinded - similar to  templateButtonComplete but bind  BorderBrush and  BorderThickness to it's parent button. Is it possible to bind also CornerRadius ?
  • styleButton - style add property such as HorizontalAlignment,Margin and use templatedButtonBinded. Note that the style set BorderBrush and BorderThickness which will be used by the template binding properties


And the buttons use is really easy after the resources are defined :



Run the application and click the "Control Template" button to produce :



Visual State Manager
The VisualStateManager manages states and logic for transitioning between states of controls.
We can use the visual state manager to handle state transitions as part of the ControlTemplate

VisualStateManger has VisualStateGroups which is a collection of VisualStateGroup objects.
VisualStateGroup has two important properties :


VisualState :

  • Represent visual state of a control e.g. MouseOver
  • Has important property name storyboard which defines the apperance of the control in this state. storyboard is actually the control animation in this state

VisualTransition - represent the visual behavior when transition happens


Source sample
Templates_NK.zip



The sample has a button with ControlTemplate name templateButtonComplete. The template has Border and ContenentPresenter as before. However the template has VisualStateManger which define the behavior of pressing on the button.


VisualStateManager.xaml


Run the application and click the "Visual State Manager" to produce :





Click the button and hold it down, the color of it will change and after you release it will turn back to green.

Sharing Templates and Styles
We already know how to share Style and Template inside the same application. Now it's time to share them cross application.


MergedDictionaries
Basic idea is to put the resources e.g. Styles, Templates in a single xaml file and share this file between projects.

Source sample
Templates_NK.zip


The common resources are defined inside a xaml file called SharedResources.xaml


This file is referenced in App.xaml using MergedDictionaries property


The resources are consumed in TemplateStyleSharing.xaml


Run the application and click the "Template and Style Sharing" to produce :





Nathan

Sunday, February 26, 2012

Windows Phone Data Binding (12)

Hello

Suppose you have a Slider and you want a TextBlock to show it's value. You can implement a handler for ValueChanged event , get the value , convert to string, and set the TextBlock Text to this string.

The above is common in Silverlight, so common that it is given a special mechanism called data binding.

Data binding is actually a link between two properties, so when one property is changing also the other changes. It can also be bidirectional binding.

The binding mechanism use events internally for handling change of properties and it can be defined entirely in XAML.

Data binding is possible between two UIelements or between a UIElement an arbitrary data.



One Way Binding


Source sample
DataBinding_NK.zip


The sample implement a binding between a Slider and a TextBlock.
OneWayBinding.xaml



The central class here is Binding class.
Two important properties :

  • ElementName - name of binding source element
  • Path - path to the binding source


Note that you can write the TextBlock element in the following short cut


Actually Binding can be done also in the code behind instead of in the XAML. To show this i have added another TextBlock Name oTextBlock into the xaml


OneWayBinding.xaml


And added to Slider.xaml.cs a binding object





Run the Application and click "OneWay Binding" button , then move the slider to the right to produce





Source and target
The binding is between the properties Slider Value and TextBlock Text
The source property is oSlider.Value so ElementName is oSlider and Path is Value.
The target property is TextBlock.Text , so the Binding element is under TextBlock.Text. Binding is done on the target element




Target and mode
Target property must be backed up by dependency property (see blog) and it must also be a property of UIElement.

Binding has property name Mode which determines the direction of data flow in the binding. by default it's OneWay i.e. a change in source will be reflected in the target , but not vice verse.

Source sample
DataBinding_NK.zip
TwoWayBinding.xaml


Notice that Binding use TwoWay Mode i.e. change in source is reflected in target and vice verse.



Run the Application and click "TwoWay Binding" button , then move the slider to the right  or change the value in the TextBox to produce


Binding Converter
Binding has a property name Converter which is used to convert the data passed between source and target. For example we can use converter to make sure that the text block will be formatted e.g. no more then two digit after the floating point.

Converter is type IvalueConverter which has two methods :

  • Convert  - Convert data passed from source to target
  • ConverBack - Convert data passed from target to source

Source sample
DataBinding_NK.zip.
To illustrate this i will add a TextBox with converter.

Convertor.cs


Converter.xaml

A resource is defined type CConverter

The resource - oCConverter is used as converter

Run the Application and click "Converter" button , then move the slider to the right to produce :


Note that the last TextBox text reflect the converter action.

Remark - Binding has a property ConverterParameter which may used as parameter for the Converter. This parameter is the third argument of the methods of  IvalueConverter.

Source Definitions


The source can be defined in four ways

  • Binding.ElementName - Source is UIElement which is created on XAML
  • Binding. Source - Source is an object. Object is typcally created on ResourceDirectory and given a key
  • Binding. RelativeSource - Source is defined according to it's position relative to the target
  • DataContext - Source is defined using the DataContext property 


Binding.Source
Source is defined by using Source property of Binding.
Source is an object. Object is typically created on ResourceDirectory and given a key

Source sample
DataBinding_NK.zip
Binding is done between a source - object type CUser and target - TextBlock. To be more precise :

  • Source property Name of CUser is bind to the target Text property of a TextBlock which represent name
  • Source property Family of CUser is bind to the target Text property of a TextBlock which represent family

User.cs




BindingSource.xaml
A resource called oUser is defined with Name Nathan and Family Krasney.
Binding is performed on two TextBlocks using Source property of Binding.
A style name styleTextBlock is defined for TextBlock and used later by all TextBlocks



Run the Application and click "Binding.Source" button to produce :




Notification
Given the sample of Binding.xaml, what will happen if i will add a button which change the properties of oUser ? actually we would like the target TextBlocks to reflect the change but this will not happen. Note that oUser is type CUser which has no dependency properties so it has no notification mechanism regarding changes of it's properties values.


To overcome this that source object must implement the interface INotifyPropertyChanged

Source sample
DataBinding_NK.zip

UserNotify.cs
Notice the set - it updates the value  only in case it has changed and only in this situation it fires the PropertyChanged event. This event is handled by the binding client which update the TextBlocks Text property.


BindingSourceNotification.xaml
The file is very similar to BindingSource.xaml beside using CUserNotify instead of CUser and using the Toggle button


BindingSourceNotification.xaml.cs
Only interesting issue here is the Button handler

Run the Application and click "Binding.Source Notification" button and click the Toggle button to produce :

Click on the Toggle button cause a change in Name and Family via binding and notification,


DataContext
FrameworkElement has property name DataContext.
Binding source is defined using DataContext.
DataContext type is object
DataContext simplify individual binding in case of one common source by eliminating repetition .
DataContext is a concept which allows objects to inherits binding specification from their parents.


Source sample
DataBinding_NK.zip

The sample is actually the same as for Binding.Source beside the use of DataContext.

DataContext.xaml
Note that ContentPanel has DataContext  set to Binding object with oUser as Source. Now all children can inherit this source and Binding of the TextBlocks need only Path.


Run the Application and click "DataContext" button to produce :





RelativeSource
Source is defined according to it's position relative to the target. This is important for templates

Source sample
DataBinding_NK.zip

Source is the TexBlock.FontFamily
Target is the same TextBlock but property is Text.

RelativeSource.xaml
Self means the same element.

Run the Application and click "Binding.RelativeSource" button to produce :



Note that the FontFamily - "Portable User Interface" which is the TextBlock FontFamily appears as the TextBlock Text.






Nathan.

Tuesday, February 21, 2012

Windows Phone - Dependency Properties (11)

Hello

Dependency property give support for :

  • Data binding
  • Property change notification
  • Use in styles


A class that implement DependencyProperty must inherit the class DependencyObject DependencyObject is very common -  UIElement derive it

Register is an important static method to register dependency property . Arguments :
  • Name of dependency property
  • Type of property
  • Type of owner i.e. the class 
  •  Property metadata. Used e.g. for   PropertyChangedCallback

Return is DependencyProperty which should be set to public static readonly field in the owner class.

Source sample
DependencyProperty_NK.zip

PropertyLimitation.xaml
The page is composed of four TextBox.Two are using CSimpleGardientTextBox and two are using CBetterGradientTextBox both are using RadialGradientBrush



The style styleCGradientTextBox is defined with three colors Brown,White,Pink



CSimpleGradientTextBox.cs
CSimpleGradientTextBox is a TextBox wirh RadialGradientBrush as background. The class has properties Color1,Color2,Color3 which defines the colors of the gradient stops



CSimpleGradientTextBox has one limitation - it can not be used as Style because you will not be able to set Color1,Color2,Color3. To be able to do this you need DependencyProperty

CBetterGradientTextBox.cs
CBetterGradientTextBox overcome the limitation of CSimpleGradientTextBox  by using dependency properties.




Basically all properties Color1,Color2,Color3 are handled the same way so i will show handling one property - Color1.

Color1Property is defined as DependencyProperty by specifying :

  • The property - Color1
  • Type of Color1 - Color
  • Type of owner - CBetterGradientTextBox
  • Hanlder - OnColor1Changed , default color  of Color1 - Red


Color1 is defined using DependencyObject methods SetValue and GetValue.  It is common to say that property Color1 is backed by dependency property Color1Property.

Handler is defined 

Note that OnColor1Changed is called whenever Color1 value is changed via it's set. This is possible because set calls the DependencyObject's method - SetValue


Run the application, click the "PropertyLimitation" button to produce




First TextBox  -  colors Brown,White,Red are defined in XAML
Second TextBox - colors are not defined in XAML so the default values in the constructor Red,Green,Blue are used
Third TextBox - style is used. Colors Brown,WhitePink
Forth TextBox -  colors are not defined in XAML, colors Red, Green,Blue defined in Register are taken



Attached Properties
Attached properties is the ability of child element in XAML to set its parent property. E.g. Canvas layout has it's property Left,Top set on it's children e.g.



It is defined using the method RegisterAttached of  DependencyProperty



Nathan

Wednesday, February 15, 2012

Windows Phone - Application Bar and Standard Controls (10)

Hello

Silverlight for Windows Phone support basic controls :

And more.

ApplicationBar
ApplicationBar is somewhat like a tool bar in desktop windows application. ApplicationBar help to create consistent user experience. Up to 4 buttons are supported

For example :


Note that ApplicationBar is not part of the visual tree. It is not UIElement and it inherit directly from object class.

When the phone is held upright the ApplicationBar appears at the bottom of the phone.

All buttons (called icons) display bitmap. The bitmap should be png file 48 pixels square , the actual image should occupy 26 pixels in the middle and color should be white.
A list of icons reside on your hard disk. Mine is on C:\Program Files\Microsoft SDKs\Windows Phone\v7.1\Icons , it is recommended to use icons from dark directory for your programs.

It is also possible to use text based menu items.


It is recommended to use ApplicationBar in case you need menu and not write your own.

ApplicationBar has property name Buttons which is a collection of actually ApplicationBarIconButton.

ApplicationBarIconButton has properties :
  • Text - icon text 
  • IconUri - Uri of the icon image

and event Click which occurs when the button is clicked.

Source sample
ApplicationBar.zip

MainPage.xaml
Four ApplicationBarIconButton are defined each with Text,IconUri,Name and Click event.


MainPage.xaml.cs
Handlers for edit,save,delete are almost the same as the IsolatedStorage example in Windows Phone - Application Architecture (6)  so i see no point going over it again.

The handler for help is as follows :
Basic idea is to store help in a another page called HelpPage.xaml




Run the application to produce :


Notice edit,save,delete,help on the bottom - this is the ApplicationBar.

Click the help button to produce :





Elements and Controls


Most visual elements have the following hierarchy :

  • object
  • DepedencyObject (abstract)
  • UIElement  (abstract)
  • FrameworkElement  (abstract)

TextBlock, Image, Border, MediaElement, Shape and panel inherits FrameworkElement .

Some classes inherits Control

  • object
  • DepedencyObject (abstract)
  • UIElement  (abstract)
  • FrameworkElement  (abstract)
  • Control   (abstract)


What's the difference between element and control ?

  • Controls involves more user interaction : Button, Slider, TextBox
  • Control is build from elements :
  • Button is a Border with TextBlock
  • Slider is composed of few Rectangulars 



RangeBase

  • Control (abstract)
  • RangeBase  (abstract)
  • ProgressBar
  • Slider
  • ScrollBar

Properties :

Event



Source sample
StandardControls_NK.zip
This sample has a slider and a rectangle. Moving the slider alter the background of the rectangle. In fact it control the red portion of the background while Green=Blue=0

Slider.xaml


Slider.xaml.cs

Run the application ,click Slider button and drag the slider to the right to produce :






Button











Button is composed of elements : Border, TextBlock so the same properties apply : e.g BorderBrush for the Border and FontStyle for the TextBlock

Sample source
StandardControls_NK.zip
The sample use two buttons :

  • button with simple content - text 
  • button with more complicate content - grid with TextBlock and Bitmap.



Button.xaml


Button.xaml.cs


Run the application ,click "Button" button to produce :





Note that you can disable Button via IsEnabled


Button precedence
from first to last :

  • Local Setting - property defined for the element
  • Style Setting  
  • Theme Style
  • Property Inheritance - property defined e.g. for Page and inherited by element inside the page
  • Default Values - of the element



Other ButtonBase Controls
Basically the inheritence hirarchy is as followes

  • Control (abstract)
  • ContentControl
  • ButtonBase (abstract) 
  • Button
  • RepeatButton -  Raise its Click event repeatly from the time it is pressed until the time it is released
  •  ToggleButton - Base class for control that can change state


Source sample


The sample present CheckBox,HyperlinkButton,RepeatButton,ToggleButton,RadioButton. 
It also show that Style may be applied to base class.E.g. you can define a style whose TargetType is Control and set there e.g. Background, now every control can use this style e.g. Button or RadioButton.

OtherButtonBaseControls.xaml





Run the application ,click "Other ButtonBase Controls" button to produce :




Nathan