Using the Multi-Touch Behavior in a Windows Phone 7 Multi-Page application

In these days I’m receiving several questions in the Multi-Touch Behaviors forums about enabling Multi-Touch manipulations in Windows Phone applications composed by more than one page.

Today I’ve modified the available sample inserting an additional page containing an image enabled for translation, rotation, zoom and inertia via the usual “MultiTouchBehavior“:


Starting from release 0.6.1 it’s now possible to use the Behavior in different pages of the application, in this way enabling multi-touch in different elements of a Windows Phone 7 application.

As usually the sample code is available for download on http://multitouch.codeplex.com, check out the Visual Studio solution “SilverlightWP7MultiTouch.sln” which contains all necessary libraries.

Happy Silverlighting!

Adding / Removing the Multi-Touch Blend Behavior using C# code-behind

I’ve received several requests about the modalities of enabling multi-touch on a UI element using the Behavior available on my CodePlex project.

The traditional syntax using XAML is here:

<Image Source="Images/Desert.jpg" x:Name="image1">
    <interactivity:Interaction.Behaviors>
        <Silverlight4:MultiTouchBehavior 
            IsInertiaEnabled="True"
            IsTranslateXEnabled="True" 
            IsTranslateYEnabled="True"
            IsRotateEnabled="True" 
            IsScaleEnabled="True"
            MinimumScale="10" MaximumScale="100"
            AreFingersVisible="True"/>
    </interactivity:Interaction.Behaviors>
</Image>

What about if you want to achieve the same result using C#? Just obtain a collection of behaviors for your element and then add/remove the MultiTouchBehavior using the following syntax:

private void btnAttach_Click(object sender, RoutedEventArgs e)
{
    var behaviors = 
        System.Windows.Interactivity
        .Interaction.GetBehaviors(image1);
    behaviors.Clear();
    var mtb = new MultiTouchBehavior
    {
        IsRotateEnabled = true,
        IsScaleEnabled = true,
        IsTranslateXEnabled = true,
        IsInertiaEnabled = true,
        AreFingersVisible = true,
        MinimumScale = 20,
        MaximumScale = 200
    };
    behaviors.Add(mtb);
    mtb.Move(new Point(200, 150), 45, 100);
}

private void btnDetach_Click(object sender, RoutedEventArgs e)
{
    var behaviors = 
        System.Windows.Interactivity
        .Interaction.GetBehaviors(image1);
    if (behaviors.Count > 0)
    {
        behaviors.Clear();
    }
}

As usually the source code is available for download on the Multi-Touch CodePlex project (check out the SilverlightWP7MultiTouch Solution).

Oh, did I already say that it also works on Windows Phone 7? 😉

Happy Silverlighting!

Book preview: Silverlight 4 User Interface Cookbook

Check out the new book “Silverlight 4 User Interface Cookbook” by Vibor Cipan:

This is the overview taken from the publisher site:

  • The first and only book to focus exclusively on Silverlight UI development.
  • Have your applications stand out from the crowd with leading, innovative, and friendly user interfaces.
  • Detailed instructions on how to implement specific user interface patterns together with XAML and C# (where needed) code, and explainations that are easy-to-understand and follow.
  • Real world projects which you can explore in detail and make modifications as you go.
  • Written by Vibor Cipan – Microsoft MVP for Expression Blend and WPF, and Silverlight UX specialist.

I’ve just received my copy and I’m looking forward to read it in the next days!

Windows Phone 7, Multi-Touch Behaviors and the Surface samples for Silverlight

I’ve just finished some experiments using the Windows Phone 7 emulator and the “Microsoft Surface Manipulations and Inertia Sample for Microsoft Silverlightin order to enable Multi-Touch gestures using Blend Behaviors:

WP7BehaviorExpression

This new implementation, now available for download in the Expression Gallery, permits to enable Multi-Touch gestures (the usual translation, rotation, zoom and inertia) on separate User Controls available in the same container.

In this way you can apply distinct Multi-Touch manipulations (inertia included) to single elements using a single code in xaml:


  <canvas>
      
          
               
          
      

      
          
             
          
      
  </canvas>

Alternatively you can use Blend inserting a reference to the project MultiTouch.Behaviors.Silverlight.WP7 and then dragging the MultiTouchManipulationBehavior from the Assets section to the  control to be touch-enabled:

Multi-Touch Behavior Blend

 

Considerations

This one has been an interesting exercise in porting code written for Silverlight to Windows Phone: I had only to create a Windows Phone 7 project and add to it the code already available for the Silverlight version and all worked well quite quickly.

Limitations

At this time the behavior works only in the fixed Portrait orientation of Windows Phone: if you change to Landscape the manipulation doesn’t work well. I’ll have to investigate further and currently I don’t have a physical device to test (I’d really love to have a device to try it :)).

Happy Silverlighting!

Enabling Multi-touch gestures in WPF using Expression Blend 4 RC and the TranslateZoomRotate behavior

I’ve already blogged about adding multi-touch support to Silverlight applications using Blend behaviors (you can also read my italian language article).

This is a powerful and simple approach which is now available in WPF using Expression Blend 4 RC and the TranslateZoomRotateBehavior.

Let’s try to build a simple example:

1 – Open Expression Blend and create a new WPF project:

 2 – Drag a Rectangle in the MainWindows.xaml:

3 – Let’s add multi-touch gestures and inertia effects to the rectangle selecting the Assets->Behavior tab and dragging the TranslateZoomRotateBehavior inside the rectangle:

4 – Let’s examine the Properties:

It’s possible to set the supported gestures (All, None, TranslateX, TranslateY, Rotate, Scale), the constrainToParentBounds modality, the Minimum, Maximum Scale and the Rotational and Translate Friction associated to the inertia.

Let’s select the constrainToParentBounds check box and run the project using the Project->Run Project menu:

Cool, Multi-touch and inertia effects are now enabled for the rectangle without writing a line of code!

And this is the generated xaml:

<Window
	xmlns="http://schemas.microsoft.com/winfx/ 2006/xaml/presentation"
	xmlns:x="http://schemas.microsoft.com/winfx/ 2006/xaml"
	xmlns:i="http://schemas.microsoft.com/expression/ 2010/interactivity"
	xmlns:ei="http://schemas.microsoft.com/expression/ 2010/interactions"
	x:Class="WpfApplication1.MainWindow"
	x:Name="Window"
	Title="MainWindow"
	UseLayoutRounding="True"
	Width="640" Height="480">

	<Grid x:Name="LayoutRoot">
		<Rectangle Margin="149,106,133,191" Stroke="Black">
			<i:Interaction.Behaviors>
				<ei:TranslateZoomRotateBehavior ConstrainToParentBounds="True"/>
			</i:Interaction.Behaviors>
			<Rectangle.Fill>
				<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
					<GradientStop Color="Black" Offset="0"/>
					<GradientStop Color="#FF8F98CA" Offset="1"/>
				</LinearGradientBrush>
			</Rectangle.Fill>
		</Rectangle>
	</Grid>
</Window>

The source code of the project is available for download here.

A Silverlight / Expression Blend behavior to add Multi-Touch Manipulation and Inertia

I’ve updated the behavior available in the Expression Community gallery adding Multi-Touch manipulation (translation, rotation and zoom) and inertia effects using code from the Surface Manipulations and Inertia Sample for Microsoft Silverlight.

To enable Multi-Touch in your code simply download the behavior from here, add the project “MultiTouch.Behaviors.Silverlight” to a Visual Studio solution and then enable the gestures in XAML:

<UserControl x:Class="SilverlightMultiTouch.MainPage"
...
xmlns:interactivity="clr-namespace:System.Windows.Interactivity; assembly=System.Windows.Interactivity"
xmlns:behaviors="clr-namespace:MultiTouch.Behaviors.Silverlight; assembly=MultiTouch.Behaviors.Silverlight"
...
>

<Canvas>
  <Image Source="Images/Desert.jpg">
     <interactivity:Interaction.Behaviors>
         <behaviors:MultiTouchManipulationBehavior InertiaEnabled="True" TouchRotateEnabled="True" TouchTranslateEnabled="True" TouchScaleEnabled="True"/>
     </interactivity:Interaction.Behaviors>
  </Image>

  <Image Source="Images/Jellyfish.jpg">
     <interactivity:Interaction.Behaviors>
         <behaviors:MultiTouchManipulationBehavior InertiaEnabled="True" TouchRotateEnabled="True" TouchTranslateEnabled="True" TouchScaleEnabled="True"/>
     </interactivity:Interaction.Behaviors>
  </Image>
</Canvas>

The MultiTouchManipulationBehavior also contains some dependency properties (TouchRotateEnabled, TouchTranslateEnabled, TouchScaleEnabled and InertiaEnabled) to enable the corresponding gestures.

The example contains Multi-Touch manipulations applied to some Image controls and a Smooth streaming player of the Silverlight Media Framework.

I’ve also posted to CodePlex a sample using WPF 4 based on the article “Introduction to WPF 4 Multitouch” by Jaime Rodriguez.

Hope this helps and Happy Silverlighting!

Get Started with Silverlight 3 and Expression Blend 3 – A full course

I’ve recently found on Twitter (thanks to Arturo Toledo) a well-done and complete course (100-200 level content) about Silverlight 3 and Expression Blend 3, containing material for students, instructors and sample code.

Topics include:

  • Animations and basic interactivity;
  • Visual State Manager;
  • Data Binding;
  • SketchFlow prototyping;
  • Video & Media;
  • DeepZoom;
  • Intro to Silverlight 3 programming.

You can download it from here: http://is.gd/2T3gk

Don’t forget to visit the “Learn” section of the Expression site to find other useful resources, videos, tutorials and starter kits:

http://expression.microsoft.com/en-us/cc197141.aspx

Happy Blending and Silverlighting!

A WPF custom control for enabling Windows 7 Multi-touch gestures

Windows 7 is now available, it’s time to build new user experiences using the new stuff, like multi-touch!

To play with this new feature, I have started a Codeplex project at http://multitouch.codeplex.com containing a first WPF custom control (and some Silverlight 3 behaviors, check out the next posts for more info) to enable touch drag, zoom and rotation gestures using the .NET wrapper classes available on http://code.msdn.microsoft.com/WindowsTouch (see also my other post about the same topic).

The touch events are managed in the ApplyTemplate method:

       public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            if (Windows7.Multitouch.TouchHandler. DigitizerCapabilities.IsMultiTouchReady)
            {
                //Find the Window containing the CustomControl
                DependencyObject dpParent = this;
                do { dpParent = LogicalTreeHelper.GetParent(dpParent); } while (dpParent.GetType().BaseType != typeof(Window));
                //Enable Stylus events
                if (dpParent != null) Factory.EnableStylusEvents(dpParent as Window);

                //Get the touch Area
                UIElement touchArea = (UIElement)GetTemplateChild("_touchArea");

                //Handle Stylus events
                if (touchArea != null)
                {
                   this.StylusDown += (s, e) => { _processor.ProcessDown((uint)e.StylusDevice.Id, e.GetPosition(touchArea).ToDrawingPointF()); };
                   this.StylusUp += (s, e) => { _processor.ProcessUp((uint)e.StylusDevice.Id, e.GetPosition(touchArea).ToDrawingPointF()); };
                   this.StylusMove += (s, e) => { _processor.ProcessMove((uint)e.StylusDevice.Id, e.GetPosition(touchArea).ToDrawingPointF()); };

                   //Handle the ManipulationDelta and the gestures
                   this._processor.ManipulationDelta += ProcessManipulationDelta;
                   this._processor.PivotRadius = 2;
                }
            }
        }

When the ManipulationDelta event occurs, the ProcessManipulationDelta handler applies the Rotate, Translate and Scale transforms:

        private void ProcessManipulationDelta(object sender, ManipulationDeltaEventArgs e)
        {
            if (this.MultiTouchEnabled)
            {
                TranslateTransform _translate = (TranslateTransform)GetTemplateChild("_translate");
                if (_translate != null)
                {
                    _translate.X += e.TranslationDelta.Width;
                    _translate.Y += e.TranslationDelta.Height;
                }

                RotateTransform _rotate = (RotateTransform)GetTemplateChild("_rotate");
                if (_rotate != null)
                    _rotate.Angle += e.RotationDelta * 180 / Math.PI;

                ScaleTransform _scale = (ScaleTransform)GetTemplateChild("_scale");
                if (_scale != null)
                {
                    _scale.ScaleX *= e.ScaleDelta;
                    _scale.ScaleY *= e.ScaleDelta;
                }
            }
        }

A dependency property named MultiTouchEnabled is also defined in order to enable and disable the touch features directly using XAML:

        public bool MultiTouchEnabled
        {
            get { return (bool)GetValue(MultiTouchEnabledProperty); }
            set { SetValue(MultiTouchEnabledProperty, value); }
        }

        public static readonly DependencyProperty MultiTouchEnabledProperty =
            DependencyProperty.Register("MultiTouchEnabled", typeof(bool), typeof(MultiTouchView), null);

The usage of this custom control is very simple, just wrap the code you want to touch-enable in this way:

<Window x:Class="WpfMultiTouch.MultiTouchWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/ presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="WPF Multi Touch gestures example" Width="1280" Height="800"
    xmlns:myControls="clr-namespace:MultiTouch.Controls.WPF; assembly=MultiTouch.Controls.WPF"
        >
    <Canvas Background="Black">
        <myControls:MultiTouchView MultiTouchEnabled="True">
            <myControls:MultiTouchView.Template>
                <ControlTemplate>
                    <Canvas x:Name="_touchArea">
                        <Viewbox RenderTransformOrigin="0.5, 0.5">
                            <Image Source="Images/image.png" Width="500"/>
                            <Viewbox.RenderTransform>
                                <TransformGroup>
                                    <RotateTransform x:Name="_rotate" Angle="0"/>
                                    <ScaleTransform x:Name="_scale" ScaleX="1" ScaleY="1"/>
                                    <TranslateTransform x:Name="_translate" X="0" Y="0"/>
                                </TransformGroup>
                            </Viewbox.RenderTransform>
                        </Viewbox>
                    </Canvas>
                </ControlTemplate>
            </myControls:MultiTouchView.Template>
        </myControls:MultiTouchView>
    </Canvas>
</Window>

This approach is very powerful, it’s possible to enable multi-touch gestures by simply wrapping the objects inserted in the XAML code inside the MultiTouchView custom control.

The source code is available on Codeplex, including a basic Silverlight 3 implementation using the new touch APIs and behaviors.