This is part of a series on New WPF Features
WPF supports multitouch API’s in .NET 4. You can have touch and manipulation operations on all the UI elements.
For creating a touch based app, you would need to subscribe to the events:
· TouchDown
· TouchEnter
· TouchLeave
· TouchMove
· TouchUp
The TouchEventArgs class has some helpful API
· GetTouchPoint - Returns the current position of the touch device relative to the specified element.
· TouchDevice - Gets the device that generated the event.
· Device - Gets the input device that initiated this event. (Inherited from InputEventArgs.)
To add manipulations, you first need to set the bool IsManipulationEnabled property. Once done you can now listen to the manipulation events
· ManipulationStarted
· ManipulationDelta
· ManipulationStarting
· ManipulationCompleted
You can restrict the manipulations that are allowed by specifying the ManipulationMode in the Starting event.
|
Member name |
Description |
|
None |
Manipulation events do not occur. |
|
TranslateX |
A manipulation can translate an object horizontally. |
|
TranslateY |
A manipulation can translate an object vertically. |
|
Translate |
A manipulation can translate an object. |
|
Rotate |
A manipulation can rotate an object. |
|
Scale |
A manipulation can scale an object |
|
All (default) |
A manipulation can scale, translate, or rotate an object and can occur with one point of input. |
Next you listen to the delta in the manipulations and perform the necessary transform, rotation,…
The manipulationDeltaEventArgs provides the DeltaManipulation property that you can use for
|
Name |
Description |
|
Expansion |
Gets or sets the amount the manipulation has resized in . |
|
Rotation |
Gets or sets the rotation of the manipulation in degrees. |
|
Scale |
Gets or sets the amount the manipulation has resized as a multiplier. |
|
Translation |
Gets or sets the linear motion of the manipulation. |
A sample app demonstrating the usage can be found here
Touch design guidelines can be found here
TestAPI has come out with a new release V0.4. Please do check it out.
So what’s new:
- Deep Object Comparison utility
- Text String Generation for random interesting combination of strings
- A Leak Detection API that enables the user to determine if the application is leaking
- Enhanced Combinatorial Variation Generation – supports tagged and weighted values
This is part of a series on New WPF Features
These controls have been part of the WPF toolkit on Codeplex. They are now making their way into the framework.
You can get the usage details from the codeplex site
WPF Toolkit: DataGrid Feature Walkthrough
WPF Toolkit: Visual State Manager Overview
WPF Toolkit: DatePicker and Calendar Walkthrough
<Calendar FirstDayOfWeek="Monday" />
<DatePicker FirstDayOfWeek="Monday" />

<DataGrid ItemsSource="{StaticResource myData}"/>

Have fun
This is part of a series on New WPF\XAML Features
Another new feature in XAML 2009 is the possibility of creating objects using the non-default constructors. The keyword here is x:Arguments
So creating a person object with a constructor requiring Name\Age could be written in XAML as
<local:Person>
<x:Arguments>
<x:String>Tom</x:String>
<x:Int32>21</x:Int32>
</x:Arguments>
</local:Person>
Next interesting feature is using FactoryMethods… the keyword here is x:FactoryMethod
<p:Guid x:FactoryMethod='NewGuid'/>
You could also combine x:Arguments with FactoryMethod
<coll:List x:Key='list' x:TypeArguments='x:String' x:FactoryMethod='local:Factory.CreateStringList'>
<x:Arguments>
<x:String>Mickey,Donald</x:String>
</x:Arguments>
</coll:List>

Sample app showing usage is attached
Note that XAML 2009 features work only for loose XAML in WPF.
This is part of a series on New WPF\XAML Features
XAML 2009 supports generics J .. In previous releases, if you needed to have an observableCollection for databinding you would probably have written code like
class PersonCollection:ObservableCollection<Person>{}
<l:PersonCollection>
<Person Name="Tom" />
</l:PersonCollection>
In this release, you can now write this as
<ObservableCollection x:TypeArguments='local:Person' xmlns='clr-namespace:System.Collections.ObjectModel;assembly=System' >
<local:Person Name='Tom' Age='21' />
</ObservableCollection>
…
<ListBox ItemsSource='{Binding}' DisplayMemberPath='Name'></ListBox>
Notice the use of TypeArguments to specify the collection type (Person in this case). It is used to pass the required constraints for a generic type
Lets go for some more examples. Simple Dictionary with the key\value pair being strings
<StackPanel.DataContext>
<coll:Dictionary x:TypeArguments='x:String, x:String' xmlns:coll='clr-namespace:System.Collections.Generic;assembly=mscorlib'>
<x:String x:Key='One'>1</x:String>
<x:String x:Key='Two'>2</x:String>
</coll:Dictionary>
</StackPanel.DataContext>
<ListBox ItemsSource='{Binding}' DisplayMemberPath='Key' Width='100'></ListBox>
Next we have a slightly more complicated dictionary with an object as the key\value pair. Interesting to note here is that Key
<StackPanel.DataContext>
<coll:Dictionary x:TypeArguments='p:Object, p:Object' xmlns:p='clr-namespace:System;assembly=mscorlib'>
<Point X='42' Y='3' >
<x:Key>
<Point X='100' Y='1' />
</x:Key>
</Point>
<x:Null x:Key='three' />
</coll:Dictionary>
</StackPanel.DataContext>
<ListBox ItemsSource='{Binding}' DisplayMemberPath='Value' Width='100'></ListBox>
And finally a nested dictionary sample
<StackPanel.Resources>
<coll:Dictionary x:TypeArguments='p:Object, coll:Dictionary(p:Object, p:Object)' x:Key='NestedItems'>
<coll:Dictionary x:Key='Dictionary1' x:TypeArguments='x:Object, x:Object'>
<x:String x:Key='One'>1</x:String>
<Point X='42' Y='3'>
<x:Key>
<Point X='11' Y='22' />
</x:Key>
</Point>
</coll:Dictionary>
</coll:Dictionary>
</StackPanel.Resources>
<ListBox ItemsSource='{StaticResource NestedItems}' DisplayMemberPath='Key'></ListBox>
Sample app showing the usage is attached.

Note that XAML 2009 features work only for loose XAML in WPF.
This is part of a series on New WPF Features
In previous releases, sending input through automation was tricky mainly because the app and the automation processes were separate. The app state could change between the time the input was sent and received. As an example, suppose you need to click something but before the click happens, the elements move (maybe due to resize …). In this case, some other element could get the mouse input.
To overcome this problem, we have introduced the SynchronizedInputPattern. Now the framework sees where the input is going and if its not the intended target, the input is cancelled. The sender is notified whether the input operation was successful or not and based on it can make a decision to try again.
So coming to the API, to determine if an element supports the pattern we get the property value
buttonElement.GetCurrentPropertyValue(AutomationElement.IsSynchronizedInputPatternAvailableProperty);
Next, you need to hook the events to the element so that we are notified of the operations success
|
InputReachedTargetEvent |
Identifies the event raised when the input was received by the element currently listening for the input. |
|
InputReachedOtherElementEvent |
Identifies the event raised when the input was received by an element other than the one currently listening for the input. |
|
InputDiscardedEvent |
Identifies the event raised when the input was discarded by WPF. |
Once the events are hooked, you can start listening to the specific SynchronizedInputType
SynchronizedInputType.KeyUp,
SynchronizedInputType.KeyDown,
SynchronizedInputType.LeftMouseUp,
SynchronizedInputType.LeftMouseDown,
SynchronizedInputType.RightMouseUp,
SynchronizedInputType.RightMouseDown
syncInputPattern.StartListening(SynchronizedInputType.MouseLeftButtonDown);
One thing to note is that the event fires only once. So if you need to send the input again, you will need to call the StartListening API again.
You can cancel listening by calling the Cancel() API
Sample app which shows the usage is attached. The app clicks on different controls simulating incorrect input received. The console output describes the operations being performed.
******Goal is to Click the Button******
-- Click on the List
---- Input was Discarded - Try Again clicking On TextBox nested in Button
-- Click on the Textbox inside Button
---- Input Reached Element other than Target - Try Again clicking on Button
-- Click on the Button
---- SUCCESS: Input Reached Target

This is part of a series on New WPF Features
Previously WPF only supported Pixel Shader 2.0 (PS 2.0). For this release, we added PS 3.0 support providing the benefits of more instructions, registers ....
The usage is similar as before. However, we have provided an API to determine if the shader can be run on the machine. The API’s are self-explanatory
· RenderCapability.IsPixelShaderVersionSupported(majorversion,minorVersion)
· RenderCapability. IsPixelShaderVersionSupportedInSoftware (majorversion,minorVersion)
· RenderCapability. MaxPixelShaderInstructionSlots(majorversion,minorVersion)

(snapshot of app on a PS2.0 supported machine)
Sample project attached.
Pre .NET 4, from a UI automation perspective, virtualization was not a good story. There wasn’t a standard way of dealing with virtualized controls, since some would expose only the visual elements while the others would create an automation tree that had every element. To fix this problem, in .NET 4, we have introduced 2 new UIA patterns: ItemContainerPattern\VirtualizedItemPattern
ItemContainerPattern enables searching the whole tree irrespective of it being virtualized.
testObject.GetCurrentPattern(ItemContainerPattern.Pattern)
Search is done using the FindItemByProperty function which has 3 parameters
- AutomationElement startAfter: element to start search from. Setting to null would mean start from beginning
- AutomationProperty: Property to be used for search. Setting to null corresponds to match all properties
- Object value: Property value
Once you find the element, you can then determine if it’s virtualized by querying the IsVirtualizedItemPatternAvailable.
(bool)item.GetCurrentPropertyValue(AutomationElementIdentifiers.IsVirtualizedItemPatternAvailableProperty);
So you have the virtualized item and would like to de-virtualize it.
VirtualizedItemPattern vpattern = item.GetCurrentPattern(VirtualizedItemPattern.Pattern) as VirtualizedItemPattern;
vpattern.Realize(); // de-virtualize the object
You can also query if the ItemContainerPattern is available using the property IsItemContainerPatternAvailable.
Sample project showing usage is attached.
This is part of a series on New WPF\XAML Features
In previous releases, if you needed to reference a named object, your XAML would look something like
<Label Target='{Binding ElementName=firstNameBox}' >_Target</Label>
<TextBox Name='firstNameBox'>Uses Binding</TextBox>
In the current release (.NET 4), we introduced a built in markup extension x:Reference. This would enable referencing a named object. The above XAML can now be written as
<Label Target= '{x:Reference secondNameBox}'>_Second Target</Label>
Or
<Label Target= 'thirdNameBox' >_Third Target</Label>
The references look both forward as well as backwards
Another possibility working with named objects is to create a markupextension that calls into IXamlNameResolver to resolve a name. One scenario is having method calls in XAML like the below. We covered this is a previous post written by Shree.
<School Topper="{Call students.GetTopper}" >
<School.Class>
<Students x:Name="students">
<Student Name="Audrey" Marks="90" />
<Student Name="Bill" Marks="95" />
</Students>
</School.Class>
<!-- This is backward reference -->
<!--<School.Topper>
<Call Expression="students.GetTopper" />
</School.Topper>-->
</School>
A simple project showing the usage of x:Reference is attached

Note that XAML 2009 features work only for loose XAML in WPF.
This is part of a series on New WPF Features
In previous releases, WPF open\Save dilogs had the XP style even on Vista. Some workarounds were to use the Vista bridge library or use the winforms dialogs. For this release we fixed this issue. You now get the OS style dialogs :) ... Usage wise its the same, you get the updated behavior for free ... The pic below shows the difference.

[This is part of a series on New WPF\XAML Features]
In previous releases, when loose XAML had events in it and was loaded it would crash. In V4, there are 2 options to avoid this crash.
à On loading events are searched on the root object of the XAML file. Suppose you had the loose XAML like the below
<local:MyStackPanel
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:local ="clr-namespace:DemoApp;assembly=DemoApp">
<Button Click="Button_Click" >Date (Event on Root)</Button>
As long as the root object (in this case MyStackPanel) can be found, the event will be hooked and will work fine without a crash
à The second approach is to define a MarkupExtension that returns a delegate and assign this to the event. So you could have XAML like the below
<Button Click="{DelegateCreatingME}"/>
<Button Click="{DelegateCreatingME ChangeFontSize}" >
<Button Click="{DelegateCreatingME ChangeForeground,Brown}" />

The sample project using the CoreMVVM library is attached.
Note that XAML 2009 features work only for loose XAML in WPF.
This is part of a series on New WPF Features
One of the big improvements in 4.0 is the Cached Composition feature in graphics. This feature enables caching a live UIElement as a bitmap, which enables quick rendering of the element as a bitmap. The UIElement is user interactive and hence will respond to keyboard input, mouse clicks,… Also, transforms, effects,.. which operate on top will not cause the cache to regenerated resulting in better performance. Previously, it was common to use RenderTargetBitmap for this purpose. However, this would be at the cost of interactivity.
Lets jump into usage. You have the BitmapCache and the BitmapCacheBrush classes. The former is useful in rendering a complex UIElement while the latter facilitates better reuse of a cached element.
Usage of BitmapCache is shown below. RenderAtScale is helpful for zoom scenarios since it a cache which is multiple of the original bitmap size. Note that changing the UIElement subtree or these properties (EnableClearType\RenderAtScale) will cause the cache to be regenerated.
<Canvas.CacheMode>
<BitmapCache EnableClearType="False" RenderAtScale="2"/>
</Canvas.CacheMode>
<Canvas CacheMode="BitmapCache"/>
BitmapCacheBrush is useful when you need to paint the same content on multiple elements. A sample usage is below.
<Grid.Resources>
<Image x:Key="cachedImage" Source="Xaml.jpg" >
<Image.CacheMode>
<BitmapCache EnableClearType="False" RenderAtScale="1" SnapsToDevicePixels="False" />
</Image.CacheMode>
</Image>
<BitmapCacheBrush x:Key="cachedImageBrush" Target="{StaticResource cachedImage}" />
</Grid.Resources>
<Button Background="{StaticResource cachedImageBrush}" Content="Tile1" Grid.Column="1"/>
<Button Background="{StaticResource cachedImageBrush}" Content="Tile2" Grid.Column="2"/>
...
Got a couple of apps in place to show the usage. The one on the left shows the zoom in action while the second app applies the cacheMode on Viewport2dVisual3D.


The code is attached. Have fun
[This is part of a series on New WPF\XAML Features]
So by now most of you must have noticed the System.Xaml dll as part of your .NET 4 WPF projects. It’s a well componentized XAML stack that provides a lot of flexibility working with XAML. So at the core we a System.Xaml.XamlReader and XamlWriter which provide the base implementation and definition for a reader and writer. XamlXmlReader is a reader that reads in XAML and produces a XAML node stream. This stream is then consumed by a XamlXmlWriter XamlObjectWriter to produce the object graph. Similarly for the Save path, you have the XamlObjectReader and XamlXmlWriter.
So the Load Path looks like
XAML à XXR à Node Stream à XOW à Object Graph
The Save path would look like
Object Graph à XOR à Node Stream à XXW à XAML
Prior to .NET 4, you didn’t have access to the internals; the access points were XamlReader.Load and XamlWriter.Save in PresentationFramework. In .NET 4, we provide access to the node stream and you could manipulate this node loop. There are 7 XamlNodeType’s that you need to look out for in this node loop.
An example of a node loop could be filtering out events and unknown elements. Wouldn’t that make a nice feature in XamlPadX J..
The code below shows how we could replace the Window in the Xaml passed with a Page.
XmlReader xmlReader = XmlReader.Create(input);
XamlXmlReader reader = new XamlXmlReader(xmlReader, System.Windows.Markup.XamlReader.GetWpfSchemaContext());
XamlObjectWriter writer = new XamlObjectWriter(reader.SchemaContext);
while (reader.Read())
{
switch (reader.NodeType)
{
case XamlNodeType.StartObject:
if (!reader.Type.Name.Equals("Window"))
writer.WriteNode(reader);
else
writer.WriteStartObject(new XamlType(typeof(Page), reader.SchemaContext));
break;
case XamlNodeType.EndObject:
case XamlNodeType.StartMember:
case XamlNodeType.EndMember:
case XamlNodeType.Value:
case XamlNodeType.GetObject:
case XamlNodeType.NamespaceDeclaration:
writer.WriteNode(reader);
break;
}
}
Attached is a project that shows how events\unknown elements could be filtered.

This is part of a series on New WPF Features
In earlier versions, on trying to deploy a Full Trust Xbap, you would get a "Trust Not Granted" error. Its possible to workaround this issue by installing an assembly in the GAC that has the AllowPartiallyTrustedCallersAttribute. Another option is to install a certificate on the user machine and sign the Xbap with the certificate. Yeah, its painful and we worked on this issue for this release
Now on deployment, you would get a clickonce dialog so that the user can determine if s\he want to run the Xbap. This is really beneficial in the case of Intranet deployment. Do I hear a WOW.. :)
Below is the pictorial difference..

In addition, clicking on the More Information link open up a dialog with additional information that would enable the user to make a more knowledgeable decision about installation
