Nick's .NET Travels

Continually looking for the yellow brick road so I can catch me a wizard....

Multiple Flyout Templates for ComboBox and Changing the Header

Following my previous post Breaking apart the Windows Phone 8.1 ComboBox Style and Colors a reader asked me:
- How to vary the flyout template so that each combobox could have a different appearance
- Change the header on the flyout from the default “CHOOSE AN ITEM”

The ComboBox uses the default style for the ListPickerFlyoutPresenter which means that in order to vary the template for each ComboBox you need to change the default style. Luckily you can do this in code. Take the following XAML which declares two Styles based on the same base style for the ListPickerFlyoutPresenter with the background color varying.
<Style
    x:Key="PurpleBackgroundListPickerFlyoutPresenter"
    TargetType="ListPickerFlyoutPresenter"
    BasedOn="{StaticResource CustomListPickerFlyoutPresenter}">
    <Setter
        Property="Background"
        Value="Purple" />
</Style>
<Style
    x:Key="GreenBackgroundListPickerFlyoutPresenter"
    TargetType="ListPickerFlyoutPresenter"
    BasedOn="{StaticResource CustomListPickerFlyoutPresenter}">
    <Setter
        Property="Background"
        Value="Green" />
</Style>

In order to switch between templates you just need to change the default template using the type as the key:

private void PurpleClick(object sender, RoutedEventArgs e) {
    var purple = Application.Current.Resources["PurpleBackgroundListPickerFlyoutPresenter"];
    Application.Current.Resources[typeof (ListPickerFlyoutPresenter)] = purple;
}

private void GreenClick(object sender, RoutedEventArgs e) {
    var green = Application.Current.Resources["GreenBackgroundListPickerFlyoutPresenter"];
    Application.Current.Resources[typeof(ListPickerFlyoutPresenter)] = green;
}

The second part is a little harder to track down because it doesn’t appear that the text “CHOOSE AN ITEM” is set anywhere but it’s being set on the TitlePresenter TextBlock in the ListPickerFlyoutPresenter template. Often by removing named items in the default template you can raise an internal exception. Luckily in this case you can simply remove the TitlePresenter element and replace it with a similar TextBlock containing the header you want. Setting the TitlePresenter to Collapsed doesn’t work as it’s set to Visible by the ComboBox so you actually need to either remove the item or set the Opacity to 0.

Breaking apart the Windows Phone 8.1 ComboBox Style and Colors

Yesterday I had an interesting, if not a little frustrating, time pulling apart the default style of the Windows Phone 8.1 ComboBox. Before I start I’ve put together a series of images showing various states of the ComboBox:

A – The default unfocused state of the ComboBox, showing the placeholder text
B – The state when an item has been selected (focused and unfocused look the same)
C – The pressed state, prior to items selection showing
D – The expanded state when only a few items (5 or less) in the list using one of the default TextBlock styles (we’ll discuss this in a minute)
E – The expanded state when only a few items (5 or less) in the list using a TextBlock without the Foreground color set (no selection)
F – The expanded state when only a few items (5 or less) in the list using a TextBlock without the Foreground color set (item selected)
G – The disabled (ie IsEnabled=false) state
H – The expanded state when more than 5 items, which is same regardless of whether an item is selected or not (ie no selection shown)

image

 

Don’t Use Any of the Built In TextBlock Styles!!!

Before we jump into look at the ComboBox styles and colors in more detail, let me briefly discuss D in more detail. For this particular scenario the combobox has 3 items in it which means that the expanded view will show the items in situ (same behaviour as the ListPicker from Windows Phone 8/8.1 Silverlight). The ItemTemplate for the ComboBox looks like the following:

<DataTemplate x:Key="ItemsItemTemplate">
    <TextBlock Text="{Binding Property1}" Style="{StaticResource BodyTextBlockStyle}" />
</DataTemplate>

On face value this looks great – we have a simple TextBlock which is data bound and we’re using one of the out of the box styles, BodyTextBlockStyle. Unfortunately this inherits from BaseTextBlockStyle which sets the Foreground based on the current theme, as the following XAML snippet illustrates.

<Style x:Key="BaseTextBlockStyle" TargetType="TextBlock">
    …….
    <Setter Property="Foreground" Value="{ThemeResource PhoneForegroundBrush}"/>
    …….
</Style>

<Style x:Key="BodyTextBlockStyle" BasedOn="{StaticResource BaseTextBlockStyle}" TargetType="TextBlock">
    <Setter Property="LineHeight" Value="24"/>
</Style>

The issue with this is that the in situ expanded view relies on Foreground being inherited from the host control, which doesn’t happen if it is explicitly set on an element (such as this case where the Foreground is being explicitly set in the TextBlock Style). The work around is simple – don’t use the built in styles, start by taking a copy of them and working with those instead eg:

<Style x:Key="NoForegroundBaseTextBlockStyle" TargetType="TextBlock">
    <Setter Property="FontFamily" Value="{ThemeResource PhoneFontFamilyNormal}"/>
    <Setter Property="FontSize" Value="{ThemeResource TextStyleLargeFontSize}"/>
    <Setter Property="TextTrimming" Value="Clip"/>
    <Setter Property="TextWrapping" Value="WrapWholeWords"/>
    <Setter Property="LineHeight" Value="21.5"/>
    <Setter Property="LineStackingStrategy" Value="BaselineToBaseline"/>
    <Setter Property="TextLineBounds" Value="Full"/>
    <Setter Property="OpticalMarginAlignment" Value="TrimSideBearings"/>
</Style>
<Style x:Key="NoForegroundTextBlockStyle" BasedOn="{StaticResource NoForegroundBaseTextBlockStyle}" TargetType="TextBlock">
    <Setter Property="LineHeight" Value="24" />
</Style>

When I use the NoForegroundTextBlockStyle instead of D, when I expand the ComboBox I see E (no item selected) or F (item selected) instead. Note how they pick up the foreground colour, including the accent colour for the selected item.

 

Now for the Colors

You’d have thought that adjusting the colors throughout the combobox would be relatively straight forward. Unfortunately this is not the case but let’s start with what we can adjust without tweaking the Template of the ComboBox. Selecting the ComboBox and looking at the Properties window (VS or Blend) I can adjust the Background, Foreground and BorderBrush, as shown in the following image where I’ve set each of these to a distinct color so that we can see where they appear in the ComboBox:

image

The impact on the ComboBox is as follows (see image below):

1 – In the unselected state, the Foreground color has no impact on the color of the placeholder text but the background and border colors can clearly be seen
2 & 3 – In the selected and pressed states, again, the Foreground color has no impact
4 – In the expanded state there are no color changes
5 – In the selected state, when there are 5 or fewer items, the Foreground color is evident in the text
6 – No change to the disabled state
7 – The Foreground color is used to highlight the selected item

image

Clearly the use of these three colors hasn’t been applied consistently through the ComboBox states so we’re going to have to dig deeper in order to tweak things. I’ll start by looking at the Template for the ComboBox by right-clicking on the ComboBox, selecting Edit Template, Edit a Copy.

image

There are three components of the Template being the presenter for the header, a button and the border which will house the expanding list for when there are five or fewer items.

image

The Button is what is displayed when there are 5 or more items. Selecting the Button we can see that both Background and BorderBrush are set but the Foreground is inherited. I’ll update this to be data bound using Template Binding to the Foreground button.

image

We’ve sorted out the inconsistency in 1. This actually also sorted out the foreground color in 2 and 3. However, when the button is pressed, we still see the accent color coming through, which in most cases conflicts with the branding of our app. The question is what to replace it with…. this is an issue for another day; for now, let’s just change it to use a different static resource. Right-click on the button, select Edit Template, Edit a Copy, which will take a copy of the button template and put Blend into template editing mode. From the States window, select the Pressed state.

image

In the Objects and Timeline we can see that the Background on the Border element has been set to the accent color. I’ll select the Border and from the Properties window select Convert to New Resource from the Background.

image

I’ll name the new resource ComboBoxPressedBrush and set the color to Pink so it stands out.

Solving 4 includes fixing a few things: Background, Border, Foreground and Selected Foreground. First things first, let’s change the white background to the background set on the ComboBox. Looking at the template it would appear that the background is already set using data binding through Template binding to the Background being set on the ComboBox. However, at least two of the States in the template are adjusting the background – in fact the error shown in Blend is the result of some developer not understanding how visual state groups work, or being too lazy to establish a working set of states. Anyhow, what we want to do in this case is actually to adjust both states to remove any changes to the background property.

image

In this case we need to remove the Background property from the following states:

CommonStates - Pressed
CommonStates - Disabled
CommonStates – Highlighted
DropDownStates - Opened

Expanding the ComboBox now shows the expanded view with the correct Background color. Now onto Foreground for both the unselected and selected items. The Foreground color of the selected item is actually set correctly – it makes sense for this to be the Foreground color set on the ComboBox. However, the unselected Foreground color is currently set to a theme color, ComboBoxHighlightedForegroundThemeBrush. To override this color you can simply define another brush resource with the same name eg:

<SolidColorBrush x:Key="ComboBoxHighlightedForegroundThemeBrush" Color="#FF00F3FF"/>

We do also want to address the conflicting visual states by removing the Foreground property from the DropDownStates – Opened. Also, remove the BorderBrush from the CommonStates – Highlighted state, which will fix the border on the expanded area. That solves number 4.

5 requires no changes

Addressing 6 requires two steps. The first is to overwrite some of the built in colors that control how the ComboBox appears when it is disabled. To do this we simply create new brush resources with the same name in our application. The following resources use the same Border, Background and Foreground that I set earlier on the ComboBox, except the Opacity is set to 40%

<SolidColorBrush x:Key="ComboBoxDisabledBorderThemeBrush" Color="#9900FF00" />
<SolidColorBrush x:Key="ComboBoxDisabledForegroundThemeBrush" Color="#990000FF" />
<SolidColorBrush x:Key="ComboBoxDisabledBackgroundThemeBrush" Color="#99FF0000" />

The other part is to adjust the Disabled state of the FlyoutButton. As I did earlier I needed to edit the Template for the Button and set the disabled BorderBrush, Background and Foreground to the corresponding ComboBoxDisabled brush.

7 requires a bit more exploration of what happens when the ComboBox expands to full screen in order to see the list of items. When this happens a flyout is displayed using the ListPickerFlyoutPresenter. The template for this control can be found in C:\Program Files (x86)\Windows Phone Kits\8.1\Include\abi\Xaml\Design\generic.xaml. Copying this template into the application resources means we can make changes, in this case to the Foreground and Background colors:

<SolidColorBrush x:Key="ComboBoxFullScreenExpandedBackgroundThemeBrush" Color="DarkGray" />
<SolidColorBrush x:Key="ComboBoxFullScreenExpandedForegroundThemeBrush" Color="Orange" />

<Style TargetType="controls:ListPickerFlyoutPresenter">
    <Setter Property="Foreground" Value="{StaticResource ComboBoxFullScreenExpandedForegroundThemeBrush}" />
    <Setter Property="Background" Value="{StaticResource ComboBoxFullScreenExpandedBackgroundThemeBrush}" />
    ….

The only thing this doesn’t affect is the header on the flyout page which still appears in white. To get this to use the Foreground value I just set I need to modify the FlyoutPickerTitleTextBlockStyle built in style (which is also in the generic.xaml file) by copy it into the application resources and altering the BasedOn value to use the NoForegroundBaseTextBlockStyle defined earlier.

<Style x:Key="FlyoutPickerTitleTextBlockStyle" TargetType="TextBlock" BasedOn="{StaticResource NoForegroundBaseTextBlockStyle}">
    ……
</Style>

With these changes made we’ve got much better control over how the ComboBox displays text and how the border, background and foreground colors are applied.

image

 

Hopefully in this post you’ve seen how you can jump in and alter colors throughout the ComboBox templates. There are a series of built in colors both in generic.xaml and themeresources.xaml (C:\Program Files (x86)\Windows Phone Kits\8.1\Include\abi\Xaml\Design) which can be overwritten to do simple changes but sometimes you need to modify the underlying templates.

When Lists aren’t Vertical or Horizontal – Going Diagonal with Windows ListView Control

The designer for a project we’re currently working on just pitched an idea where there would be a list of items that were presented along a diagonal. Back in Silverlight this probably would have been accomplished using a PathListBox but of course that doesn’t exist in the Windows 8 world. So this got me thinking …. and actually I had to reach out to UX guru Shane Morris for some inspiration. Whilst I’m not using the viewbox suggestion he had, the solution was much easier than I initially thought and essential revolves around rotating the ListView one direction and the items in the list back the other way (so they’re still horizontal).

My first pass was literally just that. A rotate transform of 27 degrees on the ListView and then a –27 degree rotate on the first item in the ItemTemplate:

<ListView>
    <ListView.RenderTransform>
        <CompositeTransform
            Rotation="27" />
    </ListView.RenderTransform>
</ListView>

<DataTemplate
    x:Key="MyItemTemplate">
    <Grid
        RenderTransformOrigin="0.5,0.5">
        <Grid.RenderTransform>
            <CompositeTransform
                Rotation="-27" />
        </Grid.RenderTransform>
        <!--     .... -->
    </Grid>
</DataTemplate>

Unfortunately this didn’t work particularly well as it ended up with too many layout issues (see below image). There was incorrect header/footer spacing but more importantly the hover effect (ie the grey background) wasn’t being rotated.

image

My next attempt involved still rotating the ListView but instead of rotating a child of the ItemTemplate I instead rotated the ListViewItemPresenter which is found by right-clicking on the ListView and selecting Edit Additional Templates, Edit Generated Item Container (ItemContainerStyle), Edit a Copy (first time only).

image

<ListViewItemPresenter .... RenderTransformOrigin="0.5,0.5">
    <ListViewItemPresenter.RenderTransform>
        <CompositeTransform Rotation="-27"/>
    </ListViewItemPresenter.RenderTransform>
</ListViewItemPresenter>

Now we’re getting closer – the hover aligns with the item as they’re both being correctly rotated. I still had issues with the positioning on the screen to ensure items scroll all the way to the edge of the screen and that all of them can still be scrolled completely into view. Firstly, I had to adjust the position of the ListView so that after rotating the trailing corner is flush with the top and bottom of the screen.

image

Doing this will prevent the first and last item being able to be scrolled into view. This can be fixed by adding a spacer into the header and footer template of the ListView.

The last issue to overcome is that the scroll bar goes off the screen at the bottom.

image

This can be fixed by tweaking the template of the scrollviewer, setting a bottom margin to lift the vertical scrollbar back onto the screen. To get to this template you have to edit the template of the ListView (not one of the additional templates), then edit the template of the ScrollViewer (which itself is part of the ListView template).

The result is that we have items that are presented, and scroll, along a diagonal line.

image

Windows Phone 8.1 APPX Code Signing Weird Error When Installing

Over the last couple of days I’ve been trying to diagnose what we were doing wrong when code signing a Windows Phone 8.1 APPX file in preparation for enterprise distribution. The signing process completes successfully. However, when we go to install the application on either device or emulator we were seeing weird errors (see image below that quotes an exception code of 0x80073CF9).

clip_image002

SOLVED: It turns out that there is an issue with the signing process but nothing related to what we were doing. It’s actually related to the version of the tools we’re using. Here’s a list of the toolsets that apparently work/don’t work:

Visual Studio 2013 with Update 2 RC – WORKS
Visual Studio 2013 with Update 2 RTM – DOESN’T WORK
Visual Studio 2013 with Update 3 RC – WORKS

So you either need to regress to the RC of Update 2, or go to the RC of Update 3.

Side Note: If you see errors relating to a missing token, you’re probably attempting to install the package by calling AddPackageAsync from within an application that isn’t signed (ie a developer build pushed out using either the application deployment tool, or via Visual Studio). If you sign the application doing the installation and then install it, you should see the the call to AddPackageAsync will work for correctly signed XAP and APPX. This is a breaking change from Windows Phone 8.0 where this method worked regardless of whether the installer app was signed or not.

Using Build it Beta to Test and Deploy your Windows Phone Applications

Over the last year we’ve been working on Build it Beta to assist Windows Phone developers deploy and test their applications. To get started, follow the setup instructions for Build it Beta

image

Here’s a bit more information on each step:

Step 1: The Build it Beta application is available in both the Windows and Windows Phone Stores. In order to test an application on your Windows Phone device, the first step is to download the Build it Beta application from the store.

Step 2: After downloading and installing Build it Beta you then need to run and sign into Build it Beta. You can choose between one of the supported social network providers (Facebook, Twitter, Microsoft, Google) and use an existing or create a new set of credentials. You need to supply a valid email address so that we can identify your account. When you want to test and application you can simply send your application to upload @ builditbeta.com from the email address you entered. We’ll send you a confirmation after the application is available for testing. After signing in, you should be prompted to return to the setup instructions. Alternatively press and hold the back button and switch back to Internet Explorer where you should still have the setup instructions.

Step 3: Install the Built to Roam enterprise deployment certificate. This certificate is required in order to install applications you want to test. Rather than deploying applications via the Windows Phone store, where they’re signed with a pre-trusted certificate, in Build it Beta all applications are currently signed using the Built to Roam enterprise deployment certificate. Installing this certificate won’t affect your ability to install applications from the Windows Phone store, nor does it affect any other enterprise enrolment you may have (eg via an MDM provider).

Step 4: Install the Build it Beta Installer. Due to both technical and policy limitations on applications installed from the Windows Phone Store, Build it Beta relies on a secondary application to install the applications you want to test. Clicking the link in the setup instructions should prompt you to install this application. Unfortunately there isn’t a progress indicator or confirmation that it has been installed successfully – give this step a minute or two before moving on.

Step 5: Launch the Build it Beta Installer. This will run the installer and pair it with the main Build it Beta application. Once you’ve completed this process you’re good to go – start sending your applications to Build it Beta to test them.

 

Testing an application

When you have an application that you want to test you can send it to Build it Beta a number of ways:

Email – Simply email your xap or appx file to upload @ builditbeta.com. You’ll get a confirmation message back once the application has been ingested.

Upload – If you have Build it Beta for Windows installed you can simply double-click your xap file. The application will be uploaded to Build it Beta.

Attachment – Rename your xap file to .betaxap and email it to someone you want to test your application. Clicking the attachment will upload the application via Build it Beta for Windows Phone and make it available for the tester.

The Danger of Setting CacheMode to BitmapCache on Windows 8

This week has been full of interesting challenges as we worked to release another Windows 8 application for a client. Credit must go to the client who has set the expectation bar at an incredibly high level – I truly wish all clients had this level of respect for their brand, identity, apps, website etc. One of the challenges we came up against was with a very persistent image that refused to display correctly. By correctly I mean without any distortion, blurring, pixelation etc that happens when you incorrectly resize images. Now we only really saw this on the Surface 2 which runs at a scale factor of 140 and it was clearly evident that the image that was displayed was blurry. Following all the documentation and guidance we provided images at 100, 140 and 180 scale factors and validated that the correct image was being show by tagging each image to make them slightly unique. We also ensured that the image element was the correct size for the image and that Stretch was set to None (interesting side note – it appears that even if the element size matches the image size, if you leave Stretch to its default value of Uniform you end up with some visual distortion).

Even after doing all of that we still ended up with an image that was slightly blurry – enough that you’d have thought the image had been blown up slightly. It turns out that we had set CacheMode=BitmapCache on a parent element to ensure that when we animated the elements they would animate together. Removing the CacheMode attribute resulted in the image appearing crystal clear.

Ok, so here’s the original.

image

 

Here’s an image where the left side is taken from an element with CacheMode=BitmapCache, the right side is from an element without this attribute – spot the difference (hint, look at the edge of the spiral towards the centre)

image

 

Here’s an image where the top is taken from an element with CacheMode=BitmapCache, the bottom side is from an element without this attribute – again you should be able to see the difference.

image

 

Call out to mobile developers out there – do you care this much about your apps? If not, then you need to re-evaluate your quality bar.

Remove Tap/Mouse Down Animations on GridView and ListView for Windows 8.1

<disclaimer> The reason that the GridView and ListView have built-in animations for when a user taps or mouse-downs on an item is to provide feedback that they have indeed tapped/mouse downed on an item. I highly discourage the removal of these built-in animations as it will detract from your user experience. That said, there are times where you may need to remove these animations. For example if you nest a ListView within an item of a GridView, then, depending on what you want tappable, you’ll need to remove the animations on either the GridView or ListView.</disclaimer>

*If you’re building for Windows 8.0 then I suggest taking a look at some of the existing posts out there on how to remove storyboards from the ItemContainerStyle (eg http://stackoverflow.com/questions/10359197/windows-8-gridview-disabling-item-tap-visualization)

A lot of the discussion on the web is on how to remove various transitions from elements in Windows 8/8.1. For example setting the Transitions property to an empty TransitionsCollection. However, after setting virtually every transitions property I could find, I was still seeing the tap animation. It turns out that one solution is much simpler than I’d thought, and can be useful if you want to get rid on all the built in GridView/ListView item effects. Be warned, this will remove all those built-in effects!

Let’s walk through a simple example:

- Create a new Windows application based on the Hub App template – this will give us a GridView to work with. You can also use the Grid App if you want.

- Open the application in Blend (right-click the project and select “Open in Blend”)

- Locate a GridView to modify – we’re going to use the GridView in Section 3 of the Hub

- Right-click the GridView and select Edit Additional Templates –> Edit Generated Item Container (ItemContainerStyle) –> Edit a Copy

image

- Switch to code mode (I prefer split mode) and delete (or comment out) the GridViewItemPresenter element.

- Add an empty ContentPresenter element.

<Style x:Key="GridViewItemStyle1" TargetType="GridViewItem">
    <Setter Property="FontFamily" Value="{ThemeResource ContentControlThemeFontFamily}"/>
    <Setter Property="FontSize" Value="{ThemeResource ControlContentThemeFontSize}"/>
    <Setter Property="Background" Value="Transparent"/>
    <Setter Property="TabNavigation" Value="Local"/>
    <Setter Property="IsHoldingEnabled" Value="True"/>
    <Setter Property="Margin" Value="0,0,2,2"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="GridViewItem">
                <ContentPresenter />
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

- Run the application – you’ll notice that there is no tap animation on the GridView in section 3, yet it still responds to tap or mouse click on the item (just no visible feedback).

Note: If you have a GridView or ListView that isn’t interactive you can always either disable it or set the IsHitTestVisible property to false.

Taking Visual States Cross Platform to iOS and Android with Xamarin

Last Friday at the Windows Phone 8.1 developer training, run by Microsoft, Nokia Microsoft and Built to Roam, we asked the room how many people used Blend and knew about Visual States. I was shattered to see very few people even knew what a Visual State was, let alone use them in their code. Visual States have to be one of the most useful aspects of the XAML system allowing you to define different states for not only your pages but also controls and user controls that you create.

On Tuesday night before the Sydney Mobile .NET Developer Meetup I was talking with Lewis Benge about how developers on other platforms control aspects of their user interface. The consensus is that it’s very reactive in that as elements of their data model, or in the case of mvvmcross elements of the view model, change elements of the UI are adjusted. For example if you were displaying some form of a loading indicator whilst some data was being retrieved from a service, when the call was complete, the progress indicator would be hidden. In this simple case you might think that it’s just one line of code to show or hide the progress indicator but now repeat this two or three times and all of a sudden you have UI control code littered throughout your application logic. In the XAML world we’d simply define these as visual states and we’d move between those states as required. In fact, as you’ll see we can even represent these states within our view model so that the state, not the visual representation of the states, form part of our application logic (and can be isolated and tested independently as it can sit nicely within a PCL).

Ok, now for a more concrete example:

- File –> New Project –> Windows Phone application

- Add New Project –> Android application

(you can repeat for iOS if you want)

- Add New Project – Portable Class Library

- Manage NuGet –> Add Mvvmcross to all projects, and follow “ToDos” as required for each project

>> At this point, you want to make sure that both your Windows Phone and Android applications build and can be run. They should both launch FirstView and contain a textbox and label with databinding working so that you can change the text in the textbox and it is updated in the label.

Blending some Visual States

We’re going to add a progress bar and a piece of text to say “Loading….” whilst data is being loaded.

- Right-click the Windows Phone project and select Open in Blend

- Add a progress bar and texblock to the contentpanel element to give you the following xaml – note that both elements are currently collapsed

<Grid x:Name="ContentPanel"
        Grid.Row="1"
        Margin="12,0,12,0">
    <ProgressBar x:Name="progressBar"
                    Visibility="Collapsed" />
    <TextBlock x:Name="textBlock"
                TextWrapping="Wrap"
                Text="Loading..."
                VerticalAlignment="Center"
                HorizontalAlignment="Center"
                Margin="0,-25,0,0"
                Visibility="Collapsed" />
</Grid>

- In the States tool windows, click the “Add state group” button in the icon bar. Call the state group “LoadingStates” (this name is somewhat irrelevant as it’s never used other than in Blend to allow you to differentiate if you have multiple state groups)

- Click the “Add state” button twice to generate states “Loading” and “Loaded”

- With the Loading state selected (there should be a red border around the main design surface indicating that you’re in state editing mode) set both textblock and progressbar to visible, and set the isindeterminate property to true. If you look at the xaml you should see the following states defined:

<VisualStateManager.VisualStateGroups>
    <VisualStateGroup x:Name="LoadingStates">
        <VisualState x:Name="Loading">
            <Storyboard>
                <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)"
                                                Storyboard.TargetName="progressBar">
                    <DiscreteObjectKeyFrame KeyTime="0">
                        <DiscreteObjectKeyFrame.Value>
                            <Visibility>Visible</Visibility>
                        </DiscreteObjectKeyFrame.Value>
                    </DiscreteObjectKeyFrame>
                </ObjectAnimationUsingKeyFrames>
                <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(ProgressBar.IsIndeterminate)"
                                                Storyboard.TargetName="progressBar">
                    <DiscreteObjectKeyFrame KeyTime="0">
                        <DiscreteObjectKeyFrame.Value>
                            <System:Boolean>True</System:Boolean>
                        </DiscreteObjectKeyFrame.Value>
                    </DiscreteObjectKeyFrame>
                </ObjectAnimationUsingKeyFrames>
                <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)"
                                                Storyboard.TargetName="textBlock">
                    <DiscreteObjectKeyFrame KeyTime="0">
                        <DiscreteObjectKeyFrame.Value>
                            <Visibility>Visible</Visibility>
                        </DiscreteObjectKeyFrame.Value>
                    </DiscreteObjectKeyFrame>
                </ObjectAnimationUsingKeyFrames>
            </Storyboard>
        </VisualState>
        <VisualState x:Name="Loaded" />
    </VisualStateGroup>
</VisualStateManager.VisualStateGroups>

- If you switch between the Loading and Loaded states in Blend you should see the elements show and hide as expected. Now we need to wire up some logic to switch between these states at runtime.

- Return to Visual Studio and go to the code-behind file for the FirstView (Windows Phone project).

- Add the following code to the OnNavigatedTo method:

protected async override void OnNavigatedTo(NavigationEventArgs e)
{
    base.OnNavigatedTo(e);
    VisualStateManager.GoToState(this, "Loading", true);
    await Task.Delay(2000);
    VisualStateManager.GoToState(this, "Loaded", true);
}

- Run the Windows Phone application and observe the application switching between the two states

- Now we need to move this logic one step further away from the UI layer and have it contained within our ViewModel. We’ll also try to eliminate those pesky string literals. To do this we’ll define an enumeration in code so that we can refer to our VisualStates – the name of the enumeration doesn’t matter but the name of the enumeration values needs to match the names of the states defined in Blend

public enum FirstStates
{
    Base,
    Loading,
    Loaded
}

- To move our state logic into the ViewModel we’ll need a way to trigger the actual state change in the UI layer (ie the view). For this we’ll expose an event on the ViewModel which will include the name of the state that we want the view to transition to. We’ll start by defining a StateEventsArgs class which we’ll use to wrap the name of the state. This class includes a couple of helper methods to make it easy to generate an instance from an enumeration value, and to return an enumeration value. You might ask why we’re converting to and from strings – we’ll come back to this!

public class StateEventArgs : EventArgs
{
    public string StateName { get; private set; }

    public static StateEventArgs Create<TState>(TState state) where TState : struct
    {
        return new StateEventArgs {StateName = state.ToString()};
    }

    public TState AsState<TState>() where TState : struct
    {
        TState state = default(TState);
        Enum.TryParse(StateName, true, out state);
        return state;
    }
}

- Update the FirstViewModel to raise a StateChanged event as follows:

public void OnStateChanged(FirstStates state)
{
    if (StateChanged != null)
    {
        StateChanged(this, StateEventArgs.Create(state));
    }
}
public override async void Start()
{
    base.Start();
    await Task.Yield(); // Attach state changed event handler

    OnStateChanged(FirstStates.Loading);
    await Task.Delay(5000);
    OnStateChanged(FirstStates.Loaded);
}
public event EventHandler<StateEventArgs> StateChanged;

- Now, in the code behind for our FirstView we can amend the OnNavigatedTo method to wire up a StateChanged event handler:

protected async override void OnNavigatedTo(NavigationEventArgs e)
{
    base.OnNavigatedTo(e);
    (ViewModel as FirstViewModel).StateChanged += FirstView_StateChanged;
}

void FirstView_StateChanged(object sender, StateEventArgs e)
{
    VisualStateManager.GoToState(this, e.StateName, true);
}

- When you run this, there is a 5 second delay during the Start method in the FirstViewModel during which the Loading state should be visible. There after it should revert to the Loaded state.

- Let’s flip across to our Android project and amend the FirstView to include the following xml.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="
http://schemas.android.com/apk/res/android"
    xmlns:local="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textSize="40dp"
        local:MvxBind="Text Hello" />
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textSize="40dp"
        local:MvxBind="Text Hello" />
    <Button
        android:id="@+id/MyButton"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/Hello" />
    <ProgressBar
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/progressBar1" />
</LinearLayout>

- Note that unlike in XAML for Windows Phone we can’t define the visual states in xml. Instead we define them as a set of Actions which will be invoked when transitioning to a particular state. In this case we’re setting the progress bar to indeterminate and changing the button color for Loading state. You’ll notice that unlike in XAML where we could rely on the state manager to revert state changes (ie Loaded state simply reverses any changes applied by the Loading state), here we have to be explicit about all changes we want to occur.

private IDictionary<FirstStates, Action> states;
protected override void OnCreate(Bundle bundle)
{
    base.OnCreate(bundle);
    SetContentView(Resource.Layout.FirstView);

    var button = FindViewById<Button>(Resource.Id.MyButton);
    button.Click += (s,e) => ViewModel.Start();

    var progress = FindViewById<ProgressBar>(Resource.Id.progressBar1);

    states = new Dictionary<FirstStates, Action>()
    {
        {FirstStates.Loading, () =>
        {
            progress.Indeterminate = true;
            button.SetTextColor(new Color(0,255,0));
        }},
        {FirstStates.Loaded, () =>
        {
            progress.Indeterminate = false;
            button.SetTextColor(new Color(255,0,0));
        }}
    };
}

- The final piece is to wire up an event handler to the StateChanged event, the same as we did for Windows Phone:

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

    (ViewModel as FirstViewModel).StateChanged += FirstView_StateChanged;
}

void FirstView_StateChanged(object sender, StateEventArgs e)
{
    var state = e.AsState<FirstStates>();
    var change = states[state];
    change();
}

- When the StateChanged event is trigger, we find the appropriate Action by looking in the state Dictionary. The Action is then invoked to apply the appropriate visual changes.

In this post I’ve walked you through the basics of how you can use visual states across both Android and Windows Phone, controlled from within your view models. This same model can be applied to iOS and of course the code for wiring up the state changed event can be abstracted into base view models and base views so you don’t need to add it to every page.

Using Universal Share Projects for Windows Phone Silverlight 8.0 and 8.1 Upgrade Path

Of course with the announcement of Windows Phone 8.1 XAML applications (ie applications for WP8.1 written in Windows XAML) and support for Universal applications, not everyone is going to immediately rebuild their Windows Phone application. Instead, existing developers need a mechanism to upgrade to the new runtime to leverage the new features without having to redeveloper all their pages. This is where Silverlight 8.1 applications come in.

There is only minimal support within Visual Studio to support developers upgrading to Silverlight 8.1, allowing them to “Retarget to Windows Phone 8.1”.

image

Retargeting works well and typically your application will continue to run. However, in most cases you’ll want to maintain both a Silverlight 8.0 and 8.1 versions of your application. An alternative is to create a copy of your Silverlight 8.0 application and upgrade that – now you have two versions of your application that you have to support. Luckily this is an area where the new Shared project support, added to enable universal applications across Windows Phone and Windows, can be used to maintain code that is used by both a Silverlight 8.0 and 8.1 application (sort of Linked files on steroids).

Steps:

- Install the Shared Project Reference Manager (http://visualstudiogallery.msdn.microsoft.com/315c13a7-2787-4f57-bdf7-adae6ed54450) – this makes creating Shared Projects much easier

- Create a new Shared Project eg MyApplication.Shared

- Unload you Windows Phone project

- Edit your Windows Phone project file

- Add a Shared Project Reference via the right-click shortcut menu on your Windows Phone project (Note: for some reason adding a shared project reference isn’t supported for Windows Phone projects, so we need to do it the manual way)

- Add Import to end of project file which references the shared project file eg

<Import Project="..\MyApplication.Shared\MyApplication.Shared.projitems" Label="Shared" />

- Reload your Windows Phone project – you should see a reference to your Shared project under References node

image

- Move as many files as possible from your Windows Phone project into the Shared project

- Note that you may experience some of these issues:

> AppResources.resx doesn’t move easily. You’ll need to make sure that both the resx and the designer.cs file are moved and that the Build Action is correct (resx file should have a Build Action of Embedded Resource and a Custom Tool of PublicResXFileCodeGenerator). You also need to remove the “.Resources” from the name of the resource being loaded and the namespace.

> You need to keep any images referenced in the WMAppManifest.xml file in the Windows Phone project. This is ApplicationIcon.png and FlipCyleTileMedium.png by default

> You still need an App.xaml file in your Windows Phone project

- Check that your Windows Phone application builds and runs (fix any build errors!)

- In Windows Explorer take a copy of your Windows Phone application and rename the folder and project files eg MyApplication.SL81

- Add the copied project into the same solution

- Right click on the project you just added and select “Retarget to Windows Phone 8.1”. Your solution structure should now look similar to the following

image

- Build and run your new Windows Phone 8.1 application

The upshot after all this is that you have a Shared project where you can store shared files across your Windows Phone Silverlight 8.0 and 8.1 applications.

Sqlite for Universal Windows and Windows Phone applications

I hadn’t tested using Sqlite with the new universal projects introduced with Visual Studio 2013 Update 2 (which includes the Windows Phone 8.1 SDK). Luckily there is already quite a bit of info out there on the bits you need to get this to work.

  1. Firstly, you need a copy of the Sqlite Extensions library updated for WP8.1. At this point this hasn’t been officially release but Tim Heuer has posted a link to his “works on my computer” version of the library. His post is Using SQL/library references in Universal Windows Apps and includes a link to the extensions library
  2. The next thing to do is to create yourself a Universal project
  3. Add a reference to the sqlite extensions library to each of the head projects (ie the Windows and Windows Phone projects, not the shared project).
  4. Next, add a nuget reference to sqlite-net (use the package with that id)
  5. In the previous step you’d see sqlite.cs and sqliteasync.cs being added to both head projects. You can copy these files into the shared project and delete them from both head projects
  6. Lastly, add some sqlite code to your shared project which can then be used by both your Windows and Windows Phone projects…. simply done!

Here’s a sample project where I followed these steps

XAML and Databinding Debugging for Windows and Windows Phone

A question that came up today during the //learn/ event was how to debug data binding in Windows and Windows Phone projects.Normally I start by checking out the Output window – in most cases any issue with data binding is usually a naming issue, which will result in a bindingexpression path error in the Output window as follows:

Error: BindingExpression path error: 'test' property not found on 'App4.MainViewModel, App4, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. BindingExpression: Path='test' DataItem='App4.MainViewModel, App4, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'; target element is 'Windows.UI.Xaml.Controls.TextBlock' (Name='null'); target property is 'Text' (type 'String')

I was reminded that Xmlspy is a great tool for diagnosing XAML issues, as well as data binding expressions. I downloaded the latest version and was surprised to see that there is full support for all types of Windows Phone 8.1 applications. The only issue I saw was getting it to attach to Windows Phone applications but this was due to my firewall getting in the way. Here’s how you can check and fix this issue:

  • Open the XAML Spy Explorer window (View menu–> Other Windows –> XAML Spy Explorer)
  • Click on the “cog” icon in the window toolbar
  • Find the “Enable remote debugging” option and set it to Yes. You’ll be prompted to permit elevated privileges (I assume to configure firewall).

image 

Now you should be good to debug your application on the emulator/device. The XAML Spy Explorer window will automatically populate with information about your application

image

Note that you can debug much more than just XAML, including sensors, storage and package deployment information.

//LEARN/ Sessions for Tomorrow

Tomorrow (24th April) we kick off the //LEARN/ event with 9 sessions delivered in English, in the Australian EST time zone. If you haven’t already registered, make sure you follow these instructions to locate the right event information on http://publishwindows.com.

I wanted to quickly share the schedule for tomorrow – you don’t need to attend the whole thing, just drop in for the sessions you want to watch. A reminder these times are for Australian Eastern Standard Time on April 24th (tomorrow from 11am!)

 

Start AEST Duration Session Presenter
11:00 AM 50mins Introduction to Windows Phone 8.1 Michael Samarin
12:00 PM 50mins Getting Started Building Windows XAML Apps William Wegerson
1:00 PM 25mins Page navigation and Data Binding Kelly White
1:30 PM 25mins Page Layout Controls & Transition Animations Nico Vermeir
2:00 PM 25mins Adapting UI for Different Screens Lwin Maung
2:30 PM 25mins Windows Runtime XAML App Lifecycle Andrei Marukovich
3:00 PM 25mins Localization, Globalization in Windows XAML Apps SENTHIL KUMAR
3:30 PM 50mins Tiles, badges and toasts and Action Centre Rob Keiser
4:30 PM 25mins Background Tasks Andrej Radinger

Debugging WebView in a Windows Phone application

In a previous post, Debugging Internet Explorer on Windows Phone 8.1, I covered how you could use the new debugging support for IE on Windows Phone to diagnose rendering issues. What I didn’t cover is how you could debug web pages when they’re hosted within an application using the WebView control.

As we’re now building for Windows XAML, we can actually use the same mechanism that’s available for Windows 8 applications (see http://www.jonathanantoine.com/2013/04/05/win8-xaml-app-how-to-debug-the-javascript-in-a-webview/ for instructions). All we need to do is change the Application process option under Debug.

image

Set this to Script and when you debug your XAML application Visual Studio will attach to the WebView allowing you to debug your script and DOM.

//learn/ Windows Phone – How to Register

Following a conversation with another developer last week I realised that it’s not particularly obvious how to register for the upcoming //learn/ Windows Phone event. If you haven’t heard about this event it’s an online webcast series hosted by Microsoft and delivered by MVPs in a number of different languages (hopefully one that suits you!). Over 6 hours you’ll learn about a lot of the key new features of Windows Phone 8.1 and how you can build awesome Universal applications for the Windows platform. If this sounds interesting, here’s how you register.

Step 1:    Go to https://publishwindows.com/

Step 2:    Scroll down until you find the section entitled “Find events and consulting times”

image

Step 3:    Select your preferred language (in this case English)

image

Step 4:    Select “Online” from the second dropdown

image

Step 5:     DON’T select Country as this will most likely eliminate all online events

image

Step 6:     Scroll down to see the list of available events and click through on the appropriate Register button for the //learn/ event

image

Note:    If you want to see the full list of languages available for //learn/ reset the Language dropdown, whilst leaving the middle dropdown set to “Online”.

image

Look forward to seeing you all online on the 24th April.

Important: Please make sure you have the correct times in your calendar – The English series starts at 11am Australian EST on the 24th (which is 6pm US PST on the 23rd!!!)

Debugging Internet Explorer on Windows Phone 8.1

The desktop version of Internet Explorer now has quite a good selection of developer tools available on any site by just pressing F12

image

Unfortunately on Windows Phone it’s been quite difficult to debug websites and so developers typically had to resort to alert(‘hello’); style debugging. With Update 2 for Visual Studio 2013 there is a new Debug menu item “Debug Windows Phone Internet Explorer”

image

This gives you the option to select the device/emulator and specify a launch site to debug.

image

The debugging experience is pretty cool as it’s actually in Visual Studio and includes the ability to set breakpoints and inspect variables.

image

Do also get the DOM Explorer

image

And the Javascript Console

image

This has got to make our jobs easier!

Upcoming Windows Platform Events for Windows and Windows Phone

Hot off the heals of //Build/ are a whole slew of local activities to get you updated and building for the new Windows platform (aka Windows and Windows Phone). Here they are:

24th April 2014    //Learn/ 

Whether you are a New Windows App Developer or an Experienced one- we have something for you!

Join us and take a deep dive into the latest features and technologies for Windows Phones, PCs and Tablets.//learn/ from our community in this “to the community, for the community and by the community” event where our MVPs and Expert Developers will help you better understand all that’s new with Windows.

Want to learn how to easily share code between store apps of different form factors? or Want to build your own Universal App? You are at the right place. These sessions will cover all the basic concepts to develop Universal Windows apps –One App for all form factors (PC, Table and Phone), Windows Phone 8.1 apps: the new application lifecycle, the new XAML etc.-with live chat and Q&A with our speakers

No need to dress up or step out you can watch and learn from the comforts of your home/office in this online webcast of informative sessions delivered by our community experts. That’s not all, our local experts will deliver these sessions in not 1 but 8 languages from across the globe(each accommodating the local time zone) to help you learn and leverage the new features and technologies.

So get started and Register Now!

17th May 2014    //Publish/

Locations TBA but Sydney, Melbourne and Brisbane are likely – more announcements to come

Whether you’re looking for expert guidance to help you get started or to cross the finish line at a local event, Microsoft experts are here to help you out every step of the way.

You can even win awards and prizes just for publishing before June 1, 2014.

Windows Phone 8.1 Developer Community Workshop

2nd May 2014 – Melbourne
9th May 2014 – Sydney
16th May 2014 - Brisbane

The Windows Phone 8.1 SDK is now available, and with it brings a wealth of new features and capabilities to take your Windows Phone applications further than before.

We've taken the best from //Build, it'll be a big day, jam packed with topics including:-

  1. The new WP 8.1 runtime
  2. Universal applications and building across WP 8.1 and Windows 8.1
  3. Bluetooth and NFC and the internet of things
  4. People Hub
  5. Notifications
  6. Javascript WinJS comes to phone Geofencing And more...

With trainers from Nokia, Microsoft, Build To Roam, and your local Windows Phone super stars, you don't want to miss out. Seats are limited, so get in fast.

Speed up Blend for Visual Studio with TFS (Visual Studio Online) using a Firewall Rule

So for the longest time I’ve complained about how unusable Blend for Visual Studio is on projects that use TFS, specifically instances of TFS that are on the other side of the internet (yes, I’m looking at you http://visualstudio.com) . The issue is that every time you try to modify a file it goes off to TFS to check something…. I’m not quite sure what, but it hangs for a couple of seconds before deciding that you’re ok to make the change. This is particularly bad when you’re working with sample data.

It turns out there is a stupidly simple fix – don’t let Blend access the internet. Due credit to Dave who works with me at Built to Roam as he was the one that told me to just create a firewall rule.

Now, it’d show you some pictures of how to create the firewall rule using MMC but for some reason MMC crashes for me when I go to view the outbound rules. Anyhow, here’s the command for doing it via the command line:

netsh advfirewall firewall add rule name="Blend" dir=out action=block program="C:\Program Files (x86)\Microsoft Visual Studio 12.0\Blend\Blend.exe"

Blend will now complain when you first open a TFS connected project but there after it won’t miss a beat as you work with files as if there is no TFS connectivity.

Built to Roam website gets a facelift with interactive Windows and Windows Phone shells

http://www.builttoroam.com

Yesterday we finally released the new version of the Built to Roam website. As most of you are aware over the last couple of years we have done a lot of work with a number of customers to help them release, or update, their Windows and/or Windows Phone applications. We wanted to showcase these as part of our interactive website, so the phone and tablet you see when the website loads are designed for you to interact with; simply tap on the phone, or swipe across and tap on the tablet, to get started

image

In interactive mode the devices move to the centre of the screen and allow you to tap through to explore information about the apps we’ve enjoyed working on. The experience for each device has been designed to reflect the interaction model of the respective platform eg the back button steps you back to the previous page.

image    image

As with all projects, there was a limit to what we could fit in the first release. As such, we made some compromises when it came to the mobile experience. Whilst the site should function correctly, particularly in portrait, the website doesn’t make good use of the available screen space. Over the coming weeks we’ll be looking to optimise the mobile experience to make it easier to browse the information on the site.

Windows Phone 8.1 Emulator

In my previous post on Windows Phone 8.1 Developer Power Tools I looked at the developer power tools that are available from within Visual Studio. In this post we’ll look at the new Windows Phone 8.1 emulator and how it is an enabler for building better applications. The first thing to note is that there are a number of different emulator images available:

image

In this brave new world of varying screen sizes Windows Phone 8.1 departs from the fixed addressable width of 480 units. Instead each device has a scale factor which results in an effective resolution – in essence this means that two devices of the same size but differing hardware resolution will display the same amount of content, whereas two devices with the same resolution but differing size, will show more/less content depending on their relative size. What this means is that we now need emulators that not only vary in resolution but also in size.

image

Here you can see both the WVGA 4inch and the 1080p 6inch alongside each other – the beauty of it being in an emulator is that it can then be resized on the screen. The thing to notice is that the 1080p emulator has an additional column of tiles which will be a typical behaviour within applications when dealing with a higher effective resolution.

The next thing to note are the additional tools that are available. Here is a quick set of screenshots – we’ll go into more details on each of these in coming posts:

image image

image image

image image

 image image