Blog

posts

Windows 10 XAML Tips: MessageDialog and ContentDialog

0 Comments
By Fons Sonnemans, 23-6-2015

In this blog post I will explain how you can show a message dialog and content dialog in your Windows 10 apps on the Desktop and Mobile (Phone) devices using C# and XAML. The MessageDialog class has been available in WinRT from the start. The ContentDialog class was introduced in Windows Phone 8.1 Universal apps and is now also available in Windows 10 because we now have a true Universal Windows Platform (UWP).

Sample Project

My sample project is a simple Windows 10 Universal app which I created using Visual Studio 2015 RC. It contains a Page with a StackPanel with 4 buttons. The first button will be used to show a message dialog. The other buttons will be used to show content dialogs.

<Page x:Class="ContentDialogDemo.MainPage"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:local="using:ContentDialogDemo"
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
      x:Name="pageRoot"
      mc:Ignorable="d">

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

        <StackPanel VerticalAlignment="Center"
                    HorizontalAlignment="Center">

            <Button Content="Show MessageDialog"
                    Click="ButtonShowMessageDialog_Click" />
            <Button Content="Show ContentDialog 1"
                    Click="ButtonShowContentDialog1_Click"
                    Margin="0,4" />
            <Button Content="Show ContentDialog 2"
                    Click="ButtonShowContentDialog2_Click" />
            <Button Content="Show ContentDialog 3"
                    Click="ButtonShowContentDialog3_Click"
                    Margin="0,4" />
        </StackPanel>

    </Grid>
</Page>

Show MessageDialog

The ButtonShowMessageDialog_Click method in the code behind of my page shows the message dialog. It creates an instance of the MessageDialog with the Text and the Title. UICommands are added to the Commands collection of the dialog. On Mobile you can only use 2 commands so there is a DeviceFamily check in the code to prevent the app from crashing. The DefaultCommandIndex is set to 0 which means that the first button will be invoked when you hit the Enter key. The CancelCommandIndex is set to 1 which means that the second button will be invoked when you hit the Escape key or the back button on the phone. You show the dialog using the ShowAsync() method which is awaited. The result contains the Id and the Label of the invoked command.

private async void ButtonShowMessageDialog_Click(object sender, RoutedEventArgs e) {

    var dialog = new Windows.UI.Popups.MessageDialog(
                "Aliquam laoreet magna sit amet mauris iaculis ornare. " +
                "Morbi iaculis augue vel elementum volutpat.",
                "Lorem Ipsum");

    dialog.Commands.Add(new Windows.UI.Popups.UICommand("Yes") { Id = 0 });
    dialog.Commands.Add(new Windows.UI.Popups.UICommand("No") { Id = 1 });

    if (Windows.System.Profile.AnalyticsInfo.VersionInfo.DeviceFamily != "Windows.Mobile") {
        // Adding a 3rd command will crash the app when running on Mobile !!!
        dialog.Commands.Add(new Windows.UI.Popups.UICommand("Maybe later") { Id = 2 });
    }

    dialog.DefaultCommandIndex = 0;
    dialog.CancelCommandIndex = 1;

    var result = await dialog.ShowAsync();

    var btn = sender as Button;
    btn.Content = $"Result: {result.Label} ({result.Id})";
}

When you run the app on your computer and click/tap the first button you get a message dialog which is centered in the app window. The default button has a blue background which is the accent color of my computer.

When you run the app on your Windows Phone and tap the first button you get a message dialog which is in the top of the screen. The dialog is dark because the phone has a dark theme setting. The labels of the buttons are always in lowercase.

Show ContentDialog

The ButtonShowContentDialog1_Click method in the code behind of my page shows the first content dialog. It creates an instance of the ConentDialog with the Title and MaxWidth. The MaxWidth property must be set to avoid problems with wide content on small devices. The Content of the dialog is set to StackPanel with the a TextBlock and a CheckBox. The IsChecked property is two-way databound to the IsPrimaryButtonEnabled property of the dialog. The Primary and Secondary buttons are initalized and use a Click event to set the result of the clicked button. If you use the Escape button or the back button on the phone the result will be set to NONE. You can only have one or two buttons.

private async void ButtonShowContentDialog1_Click(object sender, RoutedEventArgs e) {
    var btn = sender as Button;
    var dialog = new ContentDialog() {
        Title = "Lorem Ipsum",
        //RequestedTheme = ElementTheme.Dark,
        //FullSizeDesired = true,
        MaxWidth = this.ActualWidth // Required for Mobile!
    };

    // Setup Content
    var panel = new StackPanel();

    panel.Children.Add(new TextBlock {
        Text = "Aliquam laoreet magna sit amet mauris iaculis ornare. " +
                    "Morbi iaculis augue vel elementum volutpat.",
        TextWrapping = TextWrapping.Wrap,
    });

    var cb = new CheckBox {
        Content = "Agree"
    };

    cb.SetBinding(CheckBox.IsCheckedProperty, new Binding {
        Source = dialog,
        Path = new PropertyPath("IsPrimaryButtonEnabled"),
        Mode = BindingMode.TwoWay,
    });

    panel.Children.Add(cb);
    dialog.Content = panel;

    // Add Buttons
    dialog.PrimaryButtonText = "OK";
    dialog.IsPrimaryButtonEnabled = false;
    dialog.PrimaryButtonClick += delegate {
        btn.Content = "Result: OK";
    };

    dialog.SecondaryButtonText = "Cancel";
    dialog.SecondaryButtonClick += delegate {
        btn.Content = "Result: Cancel";
    };

    // Show Dialog
    var result = await dialog.ShowAsync();
    if (result == ContentDialogResult.None) {
        btn.Content = "Result: NONE";
    }
}

When you run the app on your computer and click/tap the second button you get a content dialog. The position of the dialog can differ depending the size of the app window. The OK button is only enabled when the checkbox is checked.

When you run the app on your Windows Phone and tap the second button you get a content dialog which is always in the top of the screen.

Show ContentDialog using Commands

The ButtonShowContentDialog2_Click method in the code behind of my page uses Commands instead of Events to show the result of the content dialog. The PrimaryButtonCommand is a RelayCommand which has a CanExecute which returns true when the checkbox is checked. I expected that this would disable the primary button but it doesn't. You will still have to databind the checkbox to the IsPrimaryButtonEnabled property. I hope this will change in future versions.

private async void ButtonShowContentDialog2_Click(object sender, RoutedEventArgs e) {
    var btn = sender as Button;
    var dialog = new ContentDialog() {
        Title = "Lorem Ipsum",
        //RequestedTheme = ElementTheme.Dark,
        //FullSizeDesired = true,
        MaxWidth = this.ActualWidth // Required for Mobile!
    };

    var panel = new StackPanel();

    panel.Children.Add(new TextBlock {
        Text = "Aliquam laoreet magna sit amet mauris iaculis ornare. " +
                "Morbi iaculis augue vel elementum volutpat.",
        TextWrapping = TextWrapping.Wrap,
    });

    var cb = new CheckBox {
        Content = "Agree"
    };
    panel.Children.Add(cb);
    dialog.Content = panel;

    // The CanExecute of the Command does not enable/disable the button :-(
    dialog.PrimaryButtonText = "OK";
    var cmd = new Common.RelayCommand(() => {
        btn.Content = "Result: OK";
    }, () => cb.IsChecked ?? false);

    dialog.PrimaryButtonCommand = cmd;

    dialog.SecondaryButtonText = "Cancel";
    dialog.SecondaryButtonCommand = new Common.RelayCommand(() => {
        btn.Content = "Result: Cancel";
    });

    cb.Click += delegate {
        cmd.RaiseCanExecuteChanged();
    };

    var result = await dialog.ShowAsync();
    if (result == ContentDialogResult.None) {
        btn.Content = "Result: NONE";
    }
}

Define ContentDialog in XAML

You can also use XAML instead of creating a content dialog from code. In the next example the ContentDialog is created in the MainPage.xaml and named MyContentDialog. The ButtonShowContentDialog3_Click method in the code behind will use this name to show the dialog and display the result.

<Page x:Class="ContentDialogDemo.MainPage"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:local="using:ContentDialogDemo"
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
      x:Name="pageRoot"
      mc:Ignorable="d">

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

        <StackPanel VerticalAlignment="Center"
                    HorizontalAlignment="Center">

            <Button Content="Show MessageDialog"
                    Click="ButtonShowMessageDialog_Click" />
            <Button Content="Show ContentDialog 1"
                    Click="ButtonShowContentDialog1_Click"
                    Margin="0,4" />
            <Button Content="Show ContentDialog 2"
                    Click="ButtonShowContentDialog2_Click" />
            <Button Content="Show ContentDialog 3"
                    Click="ButtonShowContentDialog3_Click"
                    Margin="0,4" />
        </StackPanel>

        <ContentDialog x:Name="MyContentDialog"
                        VerticalAlignment="Stretch"
                        Title="Lorem Ipsum"
                        PrimaryButtonText="OK"
                        IsPrimaryButtonEnabled="{Binding IsChecked, ElementName=checkBoxAgree, Mode=OneWay}"
                        SecondaryButtonText="Cancel"
                        MaxWidth="{Binding ActualWidth, ElementName=pageRoot}">
            <StackPanel>
                <TextBlock Text="Aliquam laoreet magna sit amet mauris iaculis ornare. Morbi iaculis augue vel elementum volutpat."
                            TextWrapping="Wrap" />
                <CheckBox x:Name="checkBoxAgree"
                            Content="Agree" />
            </StackPanel>

        </ContentDialog>
    </Grid>
</Page>
private async void ButtonShowContentDialog3_Click(object sender, RoutedEventArgs e) {
    var btn = sender as Button;
    var result = await MyContentDialog.ShowAsync();
    btn.Content = "Result: " + result;
}

Closure and download

I hope you can use this blog for your own Windows 10 apps. You can download the sample project below.

Cheers,

Fons

Tags: XAML, Windows10

Coding for Kids - TechDays 2015

0 Comments
By Fons Sonnemans, 1-6-2015

Op de TechDays 2015  mochten we dit jaar maar liefst 3 sessies verzorgen. De 'Coding for Kids' sessie werd gepresenteerd door Franci van der Mijden en Fons Sonnemans.  Hierbij werd duidelijk dat je kinderen kunt leren programmeren in plaats van ze alleen maar spelletjes te laten spelen. We hebben de verschillende programmeeromgevingen gedemonstreerd die er zijn om kinderen te leren programmeren. Met een opkomst van ruim 100 geïnteresseerden was de zaal volledig gevuld. Op veler verzoek kunt u de slides van deze presentatie hieronder bekijken.

We believe the children are our future. Teach them well!

Tags: TechDays

TechFriyday videos

0 Comments
By Fons Sonnemans, 26-5-2015

Op de Microsoft TechBlog heeft Microsoft Nederland een reeks van video blogs geplaats onder de noemer Tech Friday. In deze videos interviewed Clemens Schotte (Microsoft Technical Evangelist) specialisten in het vak over verschillende onderwerpen. In twee van deze video's houdt Clemens een interview met Fons Sonnemans.

Mijn eerste Windows App ontwikkelen – TechFriday, aflevering 15

Hoe moet je beginnen en wat heb je nodig om je eerste Windows of Windows Phone app te ontwikkelen? Fons Sonnemans van Reflection IT maakt je wegwijs in Visual Studio bij het bouwen van je eerste app. Je kunt Windows of Windows Phone apps ontwikkelen in verschillende programeertalen, zoals C#, VB, C++ en JavaScript. De visuele opmaaktaal is XAML of HTML, door gebruik te maken van Blend (onderdeel van Visual Studio) kun je eenvoudig schermen ontwerpen met controls en zelfs animaties die je nodig hebt in je app. Je ontwikkelde app kun je gemakkelijk testen op je huidige apparaat, maar ook met de simulator voor bijvoorbeeld een tablet of telefoon.

Mijn app in de Windows Store plaatsen – TechFriday, aflevering 16

Om een app in de Windows Store te kunnen zetten moet je eenmalig een Windows developer account aanmaken. Je hebt dan een developer-licentie. In Visual Studio – waarin je je app ook hebt gebouwd- kun je gemakkelijk je app in de Windows Store plaatsen. Fons is nogmaals bij Microsoft te gast om dit proces door te nemen.

Tags: XAML, Apps

Windows XAML Tips - ResourceDictionary with CodeBehind

0 Comments
By Fons Sonnemans, 17-4-2015

I have created XAML solutions (WPF, Silverlight, Windows Phone, Windows 8) for about 7 years now. This week I learned a new feature which I thought wasn't possible. I learned how you can place DataTemplates with eventhandlers into ResouceDictionaries. I thought this wasn't possible because ResourceDictionaries don't have CodeBehind files to write the eventhandlers in. But I was wrong. You can add a CodeBehind to a ResourceDictionary but you will have to do it manually. This makes it possible to move more DataTemplates and ControlTemplates from Pages and UserControls to ResourceDictionaries which can help to avoid duplicate XAML code.

Demo App

My demo app is a Windows app developed using the MVVM design pattern. It contains a MainPage (view), a MainViewModel (viewmodel) class and a Product (model) class. The MainViewModel has a Products property which is a list of 3 hard coded products. The MainPage has a ListView which ItemsSource is DataBound to the Products property of the MainViewModel. The ItemsTemplate of the ListView is set to the ProductsDataTemplate which is a static resource of the Page. This DataTemplate contains an Image control which has 2 events (PointerEntered and PointerExited). In this example I changed the Opacity of the image when you hover over it using your mouse. It is a silly implementation which could also have been implemented using Behaviors in Blend.

MainPage.xaml

<Page x:Class="ResourceDictionaryWithCodeBehindDemo.MainPage"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:local="using:ResourceDictionaryWithCodeBehindDemo"
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
      xmlns:vm="using:ResourceDictionaryWithCodeBehindDemo.ViewModels"
      mc:Ignorable="d">

    <Page.Resources>
        <DataTemplate x:Key="ProductDataTemplate">
            <StackPanel Orientation="Horizontal">
                <Image Source="{Binding ImageUrl}"
                       PointerEntered="Image_PointerEntered"
                       PointerExited="Image_PointerExited"
                       Opacity="0.3"
                       Width="100"
                       Height="100" />
                <StackPanel Margin="20,0">
                    <TextBlock Text="{Binding Name}" 
                               FontSize="30"/>
                    <TextBlock Text="{Binding Price}"
                               FontSize="20" />
                </StackPanel>
            </StackPanel>
        </DataTemplate>
    </Page.Resources>

    <Page.DataContext>
        <vm:MainViewModel />
    </Page.DataContext>

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <ListView Margin="50"
                  ItemsSource="{Binding Products}"
                  ItemTemplate="{StaticResource ProductDataTemplate}">
        </ListView>
    </Grid>
</Page>

The MainPage.xaml.cs file contains the MainPage class with the Image_PointerEntered and Image_PointerExited eventhandlers. They change the Opacity of the Image (sender).

public sealed partial class MainPage : Page {
    public MainPage() {
        this.InitializeComponent();
    }

    private void Image_PointerEntered(object sender, PointerRoutedEventArgs e) {
        var img = sender as Image;
        img.Opacity = 1.0;
    }

    private void Image_PointerExited(object sender, PointerRoutedEventArgs e) {
        var img = sender as Image;
        img.Opacity = 0.3;
    }
}

The MainViewModel.cs file contains the MainViewModel class which has the Products property. The Constructor adds 3 sample products to the List.

using System;
using ResourceDictionaryWithCodeBehindDemo.Models;
using System.Collections.Generic;

namespace ResourceDictionaryWithCodeBehindDemo.ViewModels {
    class MainViewModel {

        public List<Product> Products { get; set; }

        public MainViewModel() {
            this.Products = new List<Product>() {
                new Product { Name = "Computer", Price = 2000},
                new Product { Name = "Car", Price = 34000},
                new Product { Name = "Table", Price = 500},
            };
        }
    }
}

The Product.cs file contains the Product class with the Name, Price and ImageUrl properties.

using System;

namespace ResourceDictionaryWithCodeBehindDemo.Models {
    class Product {

        public string Name { get; set; }
        public double Price { get; set; }

        public string ImageUrl {
            get {
                return "http://lorempixel.com/150/150/technics/" + Name;
            }
        }
    }
}

Add ResourceDictionary

Now you can add a ResourceDictionary to the project. Created a folder Resources in the root of the Project in which you will add the ResourceDictionary file. Create this file in Blend and not in Visual Studio because Blend will add the MergedDictionary code to my App.xaml. I named my file MyDataTemplates.xaml.

Add new Item in Blend

MyDataTemplates.xaml will look like this.

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:ResourceDictionaryWithCodeBehindDemo">
    
</ResourceDictionary>

Blend will also add the ResourceDictionary to the MergedDictionary of your Application in the  App.xaml.

<Application
    x:Class="ResourceDictionaryWithCodeBehindDemo.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:ResourceDictionaryWithCodeBehindDemo">
    
	<Application.Resources>
		<ResourceDictionary>
			<ResourceDictionary.MergedDictionaries>
				<ResourceDictionary Source="Resources/MyDataTemplates.xaml"/>
			</ResourceDictionary.MergedDictionaries>
		</ResourceDictionary>
	</Application.Resources>

</Application>

Add CodeBehind to ResourceDictionary

Now you can create the MyDataTemplates.xaml.cs file in the Resources folder of the project. I do this in Visual Studio and not in Blend. In Visual Studio I have installed an the File Nesting extion (created by Mads Kristensen). This extension will automatically nest the codefile in the xaml file. It is not necessary but I like a clean solution. The complete structure of my Solution looks likes this:

Solution Explorer

Now you must add an x:Class attribute to the ResourceDictionary element in the MyDataTemplates.xaml file. This attribute points to the ResourceDictionaryWithCodeBehindDemo.Resources.MyDataTemplate class. Next you can move the ProductDataTemplate from the MainPage to the ResourceDictionary.

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        x:Class="ResourceDictionaryWithCodeBehindDemo.Resources.MyDataTemplates"
        xmlns:local="using:ResourceDictionaryWithCodeBehindDemo">

    <DataTemplate x:Key="ProductDataTemplate">
        <StackPanel Orientation="Horizontal">
            <Image Source="{Binding ImageUrl}"
                   PointerEntered="Image_PointerEntered"
                   PointerExited="Image_PointerExited"
                   Opacity="0.3"
                   Width="100"
                   Height="100" />
            <StackPanel Margin="20,0">
                <TextBlock Text="{Binding Name}"
                           FontSize="30" />
                <TextBlock Text="{Binding Price}"
                           FontSize="20" />
            </StackPanel>
        </StackPanel>
    </DataTemplate>

</ResourceDictionary>

The MyDataTemplate class must be a partial class. You must also add a constructor (use the ctor snippet) to the class and call InitializeComponent(). This InitializeComponent method will be automatically generated if you set the x:Class attribute in the XAML. Finally you can move the eventhandlers from the MainPage to the MyDataTemplates class.

using System;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;

namespace ResourceDictionaryWithCodeBehindDemo.Resources {
    partial class MyDataTemplates {

        public MyDataTemplates() {
            this.InitializeComponent();
        }

        private void Image_PointerEntered(object sender, PointerRoutedEventArgs e) {
            var img = sender as Image;
            img.Opacity = 1.0;
        }

        private void Image_PointerExited(object sender, PointerRoutedEventArgs e) {
            var img = sender as Image;
            img.Opacity = 0.3;
        }
    }
}

The App.xaml must also be changed. You will have to register an extra xml namespace named res which holds the 'using:ResourceDictionaryWithCodeBehindDemo.Resources' value. In the MergedDictionaries element you must remove the MyDataTemplates ResourceDictionary and add an <res:MyDataTemplates /> element. This will instantiate an instance of the CodeBehind class. The constructor of the class will load the XAML in the InitializeComponent() method.

<Application
    x:Class="ResourceDictionaryWithCodeBehindDemo.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    
    xmlns:res="using:ResourceDictionaryWithCodeBehindDemo.Resources"
    
    xmlns:local="using:ResourceDictionaryWithCodeBehindDemo">
    
	<Application.Resources>
		<ResourceDictionary>
			<ResourceDictionary.MergedDictionaries>
				<!--<ResourceDictionary Source="Resources/MyDataTemplates.xaml"/>-->
                <res:MyDataTemplates />
			</ResourceDictionary.MergedDictionaries>
		</ResourceDictionary>
	</Application.Resources>

</Application>

The MainPage.xaml now doesn't have the ProductsDataTemplate.

<Page x:Class="ResourceDictionaryWithCodeBehindDemo.MainPage"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:local="using:ResourceDictionaryWithCodeBehindDemo"
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
      xmlns:vm="using:ResourceDictionaryWithCodeBehindDemo.ViewModels"
      mc:Ignorable="d">

    <Page.DataContext>
        <vm:MainViewModel />
    </Page.DataContext>

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <ListView Margin="50"
                  ItemsSource="{Binding Products}"
                  ItemTemplate="{StaticResource ProductDataTemplate}">
        </ListView>
    </Grid>
</Page>

MainPage.xaml.cs now only contains the constructor.

public sealed partial class MainPage : Page {

    public MainPage() {
        this.InitializeComponent();
    }
}

Closure and download

I hope you like my solution it will open up a lot of extra possibilities to structure your XAML projects. You can download the sample project below.

Cheers,

Fons

Tags: XAML, Blend, Apps, CSharp

The hour of code

0 Comments
By Fons Sonnemans, 16-12-2014

Op vrijdag 12 december hebben we op het Varendonck-College in Asten ‘the hour of code’ georganiseerd. Ongeveer 50 leerlingen hadden zich hiervoor opgegeven. The ‘hour of code’ is een wereldwijd initiatief om leerlingen te betrekken bij de wereld achter de computer, het programmeren.

In het kader van de wereldwijde week van de informatica konden in meer dan 180 landen tientallen miljoenen leerlingen tegelijk online deelnemen aan ‘the hour of code’.

Samen met Gerard Verbrugge van Microsoft gaven we de Varendonck leerlingen een één uur durende introductie in de informatica, om hen de basispricipes van programmeren te leren.

De enthousiaste deelnemers behaalden allemaal een certificaat.


Foto: Rob Fritsen - Siris

Tags: Code, Speaker

'Twelve ways to make your apps suck less' presentation

0 Comments
By Fons Sonnemans, 21-10-2014

The Dutch and Belgium Windows and Windows Phone developers have organized the Lowlands Windows Phone Developer Day event on 18 October 2014. I have presented this 'Twelve ways to make your apps suck less' presentation. With this blog I like to share the slides and demo projects (download button below).

Twelve ways to make your apps suck less from Fons Sonnemans

I would like to thank Joost van Schaik, Nico Vermeir and Glenn Versweyveld for organizing this wonderful event.

Windows 8 XAML Tips - Trigger Behaviors

0 Comments
By Fons Sonnemans, 2-7-2014

I use Behaviors in my XAML apps all the time. I have already written a few blog post about this subject. In Silverlight and WPF there was a clear distinction between Actions, Triggers and Behaviors. Triggers are used to invoke an Action. You can use the EventTrigger, StoryBoardCompleteTrigger, KeyTrigger, TimerTrigger, PropertyChangedTrigger, DataTrigger and DataStoreTrigger. And you can easily write your own by using the Trigger 'New Item' template in Blend.

In the Windows 8.1 'Behavior SDK' the Triggers are replaced by Trigger Behaviors. You only get the DataTriggerBehavior and EventTriggerBehavior but you can write your own. With this blog post I will try to explain how to do this. I will use a TimerTriggerBehavior and a SwipeTriggerBehavior which you can use to execute actions when you active a swipe gesture on a UIElement.

TimerTriggerBehavior

Before I can explain my TimerTriggerBehavior I first have to re-introduce my Behavior<T> class which I use as a base class for all my behaviors.

public abstract class Behavior<T> : DependencyObject, IBehavior 
    where T : DependencyObject {

    [EditorBrowsable(EditorBrowsableState.Never)]
    public T AssociatedObject { get; set; }

    protected virtual void OnAttached() {
    }

    protected virtual void OnDetaching() {
    }

    public void Attach(DependencyObject associatedObject) {
        if (associatedObject == this.AssociatedObject || 
            DesignMode.DesignModeEnabled) {
            return;
        }

        this.AssociatedObject = (T)associatedObject;
        OnAttached();
    }

    public void Detach() {
        if (!DesignMode.DesignModeEnabled) {
            OnDetaching();
        }
    }

    DependencyObject IBehavior.AssociatedObject {
        get { return this.AssociatedObject; }
    }
}

The TimerTriggerBehavior class is derives from this Behavior<T> class and contains DispatcherTimer. It has a MilliSecondsPerTick and IsEnabled properties. The MilliSecondsPerTick property is used to set the Interval of the Property. The IsEnabled property is used to start and stop the timer. It is an DependencyProperty so you can DataBind it. In Tick event is subscribed in the OnAttached() method and unsubscribed in the OnDetached() method. The Timer_Tick() event handler calls the Execute() method which invokes all triggers. The class also contains an Actions DependencyProperty and a Execute() method and the class is decorated with the ContentPropertyAttribute. This will be used by Blend for Visual Studio to allow Drag&Drop of Actions onto the Behavior.

[ContentProperty(Name = "Actions")]
public class TimerTriggerBehavior : Behavior<DependencyObject> {

    private DispatcherTimer _timer = new DispatcherTimer();

    private int _millisecondPerTick = 1000;

    public int MilliSecondsPerTick {
        get { return _millisecondPerTick; }
        set {
            _millisecondPerTick = value;
            _timer.Interval = TimeSpan.FromMilliseconds(_millisecondPerTick);
        }
    }

    #region Actions Dependency Property

    /// <summary> 
    /// Actions collection 
    /// </summary> 
    public ActionCollection Actions {
        get {
            var actions = (ActionCollection)base.GetValue(ActionsProperty);
            if (actions == null) {
                actions = new ActionCollection();
                base.SetValue(ActionsProperty, actions);
            }
            return actions;
        }
    }

    /// <summary> 
    /// Backing storage for Actions collection 
    /// </summary> 
    public static readonly DependencyProperty ActionsProperty =
        DependencyProperty.Register("Actions",
                                    typeof(ActionCollection),
                                    typeof(SwipeTriggerBehavior),
                                    new PropertyMetadata(null));

    #endregion Actions Dependency Property

    protected void Execute(object sender, object parameter) {
        Interaction.ExecuteActions(sender, this.Actions, parameter);
    }

    protected override void OnAttached() {
        base.OnAttached();
        _timer.Tick += timer_Tick;
        if (this.IsEnabled) {
            _timer.Start();
        }
    }

    private void timer_Tick(object sender, object e) {
        this.Execute(this, null);
    }

    protected override void OnDetaching() {
        base.OnDetaching();
        _timer.Stop();
        _timer.Tick -= timer_Tick;
    }

    #region IsEnabled Dependency Property

    /// <summary> 
    /// Get or Sets the IsEnabled dependency property.  
    /// </summary> 
    public bool IsEnabled {
        get { return (bool)GetValue(IsEnabledProperty); }
        set { SetValue(IsEnabledProperty, value); }
    }

    /// <summary> 
    /// Identifies the IsEnabled dependency property. 
    /// This enables animation, styling, binding, etc...
    /// </summary> 
    public static readonly DependencyProperty IsEnabledProperty =
        DependencyProperty.Register("IsEnabled",
                typeof(bool),
                typeof(TimerTriggerBehavior),
                new PropertyMetadata(true, OnIsEnabledPropertyChanged));

    /// <summary>
    /// IsEnabled changed handler. 
    /// </summary>
    /// <param name="d">TimerTriggerBehavior that changed its IsEnabled.</param>
    /// <param name="e">DependencyPropertyChangedEventArgs.</param> 
    private static void OnIsEnabledPropertyChanged(DependencyObject d, 
                            DependencyPropertyChangedEventArgs e) {
        var source = d as TimerTriggerBehavior;
        if (source != null) {
            var value = (bool)e.NewValue;
            if (value) {
                source._timer.Start();
            } else {
                source._timer.Stop();
            }
        }
    }

    #endregion IsEnabled Dependency Property

SwipeTriggerBehavior

The SwipeTriggerBehavior has a Direction property which you can set the swipe direction which will trigger the Actions. The ManipulationCompleted event on the UIElement is used to detect the swipe gesture. The ManipulationCompletedRoutedEventArgs.Velocities.Linear.X and Y are used to check the direction. I use this Between() extension method to check it is between 0.3 and 100. These values work for me but maybe not for you. Maybe I should make these flexible using properties (next version).

[ContentProperty(Name = "Actions")]
public class SwipeTriggerBehavior : Behavior<UIElement> {

    /// <summary>
    /// Get/Sets the direction of the Swipe gesture 
    /// </summary>
    public SwipeDirection Direction { get; set; }

    #region Actions Dependency Property

    /// <summary> 
    /// Actions collection 
    /// </summary> 
    public ActionCollection Actions {
        get {
            var actions = (ActionCollection)base.GetValue(ActionsProperty);
            if (actions == null) {
                actions = new ActionCollection();
                base.SetValue(ActionsProperty, actions);
            }
            return actions;
        }
    }

    /// <summary> 
    /// Backing storage for Actions collection 
    /// </summary> 
    public static readonly DependencyProperty ActionsProperty =
        DependencyProperty.Register("Actions",
                                    typeof(ActionCollection),
                                    typeof(SwipeTriggerBehavior),
                                    new PropertyMetadata(null));

    #endregion Actions Dependency Property

    protected void Execute(object sender, object parameter) {
        Interaction.ExecuteActions(sender, this.Actions, parameter);
    }

    protected override void OnAttached() {
        base.OnAttached();

        this.AssociatedObject.ManipulationMode = 
            this.AssociatedObject.ManipulationMode | 
            ManipulationModes.TranslateX | 
            ManipulationModes.TranslateY;

        this.AssociatedObject.ManipulationCompleted += OnManipulationCompleted;
    }

    protected override void OnDetaching() {
        base.OnDetaching();
        this.AssociatedObject.ManipulationCompleted -= OnManipulationCompleted;
    }

    private void OnManipulationCompleted(object sender, 
                                        ManipulationCompletedRoutedEventArgs e) {

        bool isRight = e.Velocities.Linear.X.Between(0.3, 100);
        bool isLeft = e.Velocities.Linear.X.Between(-100, -0.3);

        bool isUp = e.Velocities.Linear.Y.Between(-100, -0.3);
        bool isDown = e.Velocities.Linear.Y.Between(0.3, 100);

        switch (this.Direction) {
            case SwipeDirection.Left:
                if (isLeft && !(isUp || isDown)) {
                    this.Execute(this.AssociatedObject, null);
                }
                break;
            case SwipeDirection.Right:
                if (isRight && !(isUp || isDown)) {
                    this.Execute(this.AssociatedObject, null);
                }
                break;
            case SwipeDirection.Up:
                if (isUp && !(isRight || isLeft)) {
                    this.Execute(this.AssociatedObject, null);
                }
                break;
            case SwipeDirection.Down:
                if (isDown && !(isRight || isLeft)) {
                    this.Execute(this.AssociatedObject, null);
                }
                break;
            case SwipeDirection.LeftDown:
                if (isLeft && isDown) {
                    this.Execute(this.AssociatedObject, null);
                }
                break;
            case SwipeDirection.LeftUp:
                if (isLeft && isUp) {
                    this.Execute(this.AssociatedObject, null);
                }
                break;
            case SwipeDirection.RightDown:
                if (isRight && isDown) {
                    this.Execute(this.AssociatedObject, null);
                }
                break;
            case SwipeDirection.RightUp:
                if (isRight && isUp) {
                    this.Execute(this.AssociatedObject, null);
                }
                break;
            default:
                break;
        }
    }
}

public enum SwipeDirection {
    Left,
    Right,
    Up,
    Down,
    LeftDown,
    LeftUp,
    RightDown,
    RightUp,
}

This class also contains an Actions DependencyProperty and an Execute() method. Just like the TimerTrigger. I have tried to place them in an abstract base class TriggerBehavior<> but that caused problems in Blend. You couldn't drop an action on the Triggers deriving from this class. So I have chosen to have some duplicate code.

Triggers Demo Project

To demonstrate these behaviors I have written this 'Triggers Demo' project. I Blend for Visual Studio I have dropped a TimerTriggerBehavior onto the root Grid element of the MainPage.

On the TimerTriggerBehavior I have dropped a PlaySoundAction. The Source of this action is set to a Click.wav which I added to the \Assets\Sounds folder of the project.

The Grid also contains a ToggleSwitch. The IsOn property is databound to the IsEnabled property of the timer trigger.

<ToggleSwitch Header="TimeTrigger"
                HorizontalAlignment="Left"
                Margin="114,-6,0,0"
                Grid.Row="1"
                VerticalAlignment="Top"
                OnContent="Enabled"
                OffContent="Disabled"
                IsOn="{Binding IsEnabled, ElementName=MyTimerTrigger, Mode=TwoWay}" />

I have dropped the SwipeTriggerBehavior 4 times on a blue Grid. Each with a different Direction: Up, Down, Left, Right. Inside each trigger I have dropped a ChangePropertyAction. The Value of the Text property of a TextBlock is set to the direction

<Grid Grid.Row="2"
        Margin="120,0,40,40"
        Background="#0096FF">

    <Interactivity:Interaction.Behaviors>
        <Behaviors:SwipeTriggerBehavior Direction="Up">
            <Core:ChangePropertyAction PropertyName="Text"
                                        TargetObject="{Binding ElementName=tbDemo}"
                                        Value="Up" />
        </Behaviors:SwipeTriggerBehavior>
        <Behaviors:SwipeTriggerBehavior Direction="Down">
            <Core:ChangePropertyAction PropertyName="Text"
                                        TargetObject="{Binding ElementName=tbDemo}"
                                        Value="Down" />
        </Behaviors:SwipeTriggerBehavior>
        <Behaviors:SwipeTriggerBehavior Direction="Left">
            <Core:ChangePropertyAction PropertyName="Text"
                                        TargetObject="{Binding ElementName=tbDemo}"
                                        Value="Left" />
        </Behaviors:SwipeTriggerBehavior>
        <Behaviors:SwipeTriggerBehavior Direction="Right">
            <Core:ChangePropertyAction PropertyName="Text"
                                        TargetObject="{Binding ElementName=tbDemo}"
                                        Value="Right" />
        </Behaviors:SwipeTriggerBehavior>
    </Interactivity:Interaction.Behaviors>

    <TextBlock Margin="50"
                HorizontalAlignment="Center"
                VerticalAlignment="Top"
                Style="{StaticResource HeaderTextBlockStyle}"
                Text="Swipe Up, Down, Left or Right" />

    <TextBlock x:Name="tbDemo"
                HorizontalAlignment="Center"
                VerticalAlignment="Center"
                Style="{StaticResource HeaderTextBlockStyle}" />

</Grid>

The result is a Page in which you hear a click sound play every 2 seconds. You can turn the sound off using the ToggleSwitch. If you swipe the blue box the swipe direction is shown in the center of this box.

Closure and download

I hope you like my solution. Feel free to use it in your projects. You can download the sample project below.

Cheers,

Fons

Events and code examples

0 Comments
By Roy Janssen, 2-7-2014

The last couple of months I have been speaking at a couple of events. For those who visited these events or for those who want to know more about the subject I will give a brief summary of the talks and post the slides / sample code here for you.

Azure mobile services

At the StoreAppsUG end of februari and at the SDN event last march I have been talking about Azure mobile services. In this talk I explained how to use Azure mobile services in combination with Windows 8 and Windows Phone 8. The example I have build for this is a clean example on how to do this in a simple way. You can find the slides (in Dutch) and example code here:

- Slides 

- Example code 

Kinect for Windows v2

At the TechDays in the Netherlands last april I have been talking about the new Kinect for Windows v2. As a participant in the Developer preview I had early access to the hardware and SDK. During this talk I showed a lot of the possibilities of the new Kinect for Windows sensor. You can watch my presentation online at the Channel 9 site.

Connecting hardware to Windows Phone 8

At the SDN event last june I spoke about connecting hardware to a Windows Phone 8 application. During this session I showed how you can connect and control Arduino hardware with your own Windows Phone 8 application. The Arduino hardware featured a lot of nice shining LED lights with the use of the Windows Phone application you could decide which to turn on or off. And even select the color of the RGB LED's. For now I'm only sharing the slides (in Dutch) since the code needs a little bit of cleaning up. But if you are interested in the rough code please contact me.

- Slides 

Tags: TechDays

MVP Windows Platform Development

0 Comments
By Fons Sonnemans, 1-7-2014

Vandaag ben ik voor de 2de keer uitgeroepen tot Microsoft Most Valuable Professional (MVP) op het gebied van Windows Platform Development. De titel Microsoft MVP wordt uitsluitend toegekend aan geselecteerde specialisten die zich actief inzetten voor een community rondom een Microsoft product. Microsoft beloont deze personen voor hun inzet en hulp aan de gemeenschap door middel van de titel MVP.

Microsoft MVP Logo

Tags: MVP

TechDays 2014 videos and presentations

0 Comments
By Fons Sonnemans, 31-5-2014

Op 16 en 17 april heb ik weer bij het TechDays 2014 event van Microsoft een aantal sessies gepresenteerd. Via deze blog wil ik de videos en presentaties met u delen.

What’s new in XAML and Tooling for Windows 8.1?

Channel 9 Video

SlideShare presentatie

Making money with Apps

Channel 9 Video

SlideShare presentatie

Designing XAML Apps using Blend for Visual Studio 2013

Channel 9 Video

SlideShare presentatie

 

Cheers,

Fons

Tags: TechDays, Apps, Blend, Xaml

All postings/content on this blog are provided "AS IS" with no warranties, and confer no rights. All entries in this blog are my opinion and don't necessarily reflect the opinion of my employer or sponsors. The content on this site is licensed under a Creative Commons Attribution By license.