XAML and GIS

I was looking at Stackoverflow and found a question asking about how to sync two LongListSelectors so that their scroll position was always the same. I thought this was so cool that it was worth sharing it with the masses.

First create a new class called MyLongListSelector. Unlike the ListBox, the LLS does not use a ScrollViewer to scroll the content. Instead, it uses a ViewportControl. We need to override the OnApplyTemplate and hook into the ViewportChanged event of the ViewportControl .

publicclass MyLongListSelector : LongListSelector

{

private ViewportControl _viewport;

publicoverridevoid OnApplyTemplate()

{

base.OnApplyTemplate();

_viewport = (ViewportControl)GetTemplateChild("ViewportControl");

_viewport.ViewportChanged += OnViewportChanged;

}

}

Within the event handler for the ViewportChanged event, we’ll set a DependencyProperty that represent the top of the scroll position.

When our own ScrollPosition changes, we’ll attempt to change the Viewport of the ViewportControl. We’ll do this because the value could be changing from xaml, where another control is setting it based on it’s value. We cannot set the Viewport directly, and we cannot set the top of the Viewport. Luckily the ViewportControl does have a SetViewportOrigin method that allows us to set the top of the scroll.

Notice that the two LLS are binding to each others ScrollPosition property and are using TwoWay binding. This allows each control to set the other controls position.

This approach unfortunately causes some choppy scrolling and causes the scrolling to abruptly stop. We can help control that by checking the ManipulationState of the ViewportControl before we attempt to change the value of the Viewport. If the ManipulationState is Idle, we can be pretty sure that we should set the value because the ViewportControl is not the one being animated. We want to make sure that we do not set the Viewport for the LLS that is being animated.

Usually everyone starts by saving values into IsolatedStorageSettings, and for the most part, it’s probably the best way to go. If you are creating a music app, you can not use IsolatedStorageSettings. The AudioPlayerAgent simply will not get the correct setting values. If you are creating an app with a background agent, you should consider not using IsolatedStorageSettings for the same reason as before. You are less likely to have a problem with incorrect values with a normal background agent than you are when using an audio agent.

While using the IsolatedStorageSettings can be easy, the code can get ugly fast. You may have usage scattered throughout your code.

As you can see this eventually gets out of control. Let’s take this one step further. Instead of littering our code with all of this dictionary access, why don’t we just create a class with automatic properties that has a Save and Load method.

Our code got a little better, but it’s not very extensible. Every time you add a new property you have to add keys/values to saving and loading. When you write your next app, you’ll copy and paste the file and change the strings. I enjoy reusing code, not copy/paste. I enjoy doing less work, not adding key/values for every setting property I have.

We can make this even better. We can make a reusable class, in which we do not have to worry about adding more than our auto properties. We do this with reflection and a base class.

This is the third post is a series about creating simple page transitions using Storyboards. We’ve created two basic page transitions with the slide and turnstile transition. Now it’s time to get a little more complex. The mail app has what I like to call a “fly away” transition. When you tap an email, the subject flies away and the email slides up.

This transition is a little more complex. Instead of animating the entire page, we only animate one control that is contained within one item of a ListBox. When the selection changes we need to animate the “header” of the selected item. The problem is that the SelectedItem of a ListBox is the bound item, and not the UI representation of that item. Good news is if we are displaying items with any type of ItemsControl, we can get the container for the bound item. An ItemsControl has a ItemContainerGenerator property that returns an instance of an ItemContainerGenerator. The ItemContainerGenerator has a ContainerFromItem method that returns the DependencyObject used to display the bound item.

Once we have the first TextBlock, we’ll need to animate it to the left and down. Like the Slide transition, we’ll animate the TranslateY and TranslateX properties of a CompositeTransform. We’ve been creating a lot of DoubleAnimations, so let’s make a method to help.

In the video above, I used the Windows Phone Databound App project template. By default, this template uses the new LongListSelector. Unfortunately, the LongListSelector is not supported for this transition. The LongListSelector is not an ItemsControl, and as such, does not have a way to get the generated UI element from a bound item. To use this project, you’ll need to change the LongListSelector to a ListBox.

Now that we have our transition complete, we’ll need to use it! When the selection changes, we’ll call our new extension method. We’ll also need to store the selected item to ensure that we can animate it back in when the back is navigated to.

In my last post, I talked about creating a simple transition to slide a page in or out. While that transition was functionality I needed for my app, Santa Calls, I thought it would be fun to do more of these posts. For this post we’ll create a turnstile transition. The turnstile transition is like a page turning.

For the turnstile transition, we need to use the animate the Projection of the page. We’ll set the Projection to be a PlaneProjection. To get the rotation to turn like a page would, we need to rotate around the vertical, or y-axis. The RotationY property of the PlaneProjection is how we accomplish this.

Storyboard.SetTargetProperty(animation, new PropertyPath("(UIElement.Projection).(PlaneProjection.RotationY)"));

Storyboard.SetTarget(animation, source);

story.Children.Add(animation);

await story.BeginAsync();

}

The code is very similar to the slide transition, and still very simple. Just as before, I am using Morten’s Storyboard as a Task extension method. Adding these animations to pages is the same as before. simply call the transition method on the object you want to animate.

protectedoverride async void OnNavigatedTo(NavigationEventArgs e)

{

try

{

await LayoutRoot.TransitionInTurnstile();

}

catch { }

}

Remember that we are performing an async operation within a void method, so wrap the call in a try/catch. This code shouldn’t error, but you never know.

When navigating backwards, first cancel the navigation, animate, and then navigate!

I recently updated my app Santa Calls to include a settings page that would allow the user to delay a call or pin lock the application. When navigating to this page I wanted a nice transition, but I wanted the tree in the background to remain.

To accomplish this I set the background of these pages to be the tree image and moved the content in/out when needed. I would not be able to accomplish this type of transition using an SDK like the Windows Phone Toolkit or Telerik unless I set the application background to be the tree. I did not want to do this because the phone call pages do not have this same background.

The transitions are pretty simple and can be used by any page to move content up/down. I created a handy extension method that can be used by any FrameworkElement. To slide the content up into view, we need to create a Storyboard with a DoubleAnimation that will move the content (assumed to be a page) from the bottom of the page to the top.

Storyboard.SetTargetProperty(animation, new PropertyPath("(UIElement.RenderTransform).(CompositeTransform.TranslateY)"));

Storyboard.SetTarget(animation, source);

story.Children.Add(animation);

await story.BeginAsync();

}

This uses a BeginAsync extension method from Morten Nielsen to run a Storyboard as a Task. To slide the content up or down we pass the from and to Y values to the SlideVertically method.

Now that we have our extension methods, we need to use them. When navigating to a page, override the OnNavigatedTo method and call the TransitionInSlideUp method.

protectedoverride async void OnNavigatedTo(NavigationEventArgs e)

{

base.OnNavigatedTo(e);

try

{

await LayoutRoot.TransitionInSlideUp();

}

catch { }

}

The slide out transition is a little different. You already know how to exit app when awaiting an operation. This will be very similar. Instead of exiting the app, you’ll continue to navigate backwards.

protectedoverride async void OnBackKeyPress(CancelEventArgs e)

{

e.Cancel = true;

base.OnBackKeyPress(e);

try

{

await LayoutRoot.TransitionOutSlideDown();

}

catch { }

NavigationService.GoBack();

}

With the SlideVertically method you can easily create slide updown transitions for navigating in or out.

I was looking at my site traffic and noticed that one of my most popular posts was about creating a custom MessageBox. This post was written two years ago and continues to get a lot of traffic. Since writing that post, I’ve updated my MessageBox a lot. I’ve changed it to use async/await, modified the style, corrected some bugs, and added functionality. Since I’ve made a lot of changes, and that post continues to get a lot of readers, I thought it would be good to give the latest version.

I continue to use a UserControl approach for this because I don’t want any overriding of styles. It has a set look, and should not be allowed to be changed (aside from the use of static resources). The xaml only need a small change to the bottom margin. Instead of 12 all around, it needed 18 on the bottom. I also changed the name of the first Grid from MessagePanel to LayoutRoot, this wasn’t needed, but made some code behind easier to understand what element was being modified.

The code behind saw a lot of changes as can be seen in this diff comparison from WinMerge.

The first change was to make the Show method awaitable. This requires removing the Closed event, and the use of a TaskCompletionSource. We need to wait awhile for user interaction, so we’ll create a member wide TaskCompletionSource. Bold is for new code.

The previous MessageBox fired the Closed event and then removed the MessageBox from the active page. When changing to using the TaskCompletionSource, I changed to set the result after the MessageBox was removed from the page. Within the Completed event handler of the transition, set the result.

_completeionSource.SetResult(result);

I intentionally left out most of the code of the remove method because I wanted to save the best for last. The last bit that I added is something no other custom MessageBox does. We need to account for apps that have changed the SystemTray of the page.

The MessageBox needs to change the BackgroundColor of the SystemTray to be the PhoneChromeBrush color. If the user changes the Opacity of the SystemTray to be less than 1 the MessageBox needs to account for it. If the Opacity is less than one, then the page will be shifted up into the tray. This has always bugged me about the Opacity property of the SystemTray and the ApplicationBar. Rather than just changing the opacity (whether you can see behind it), it also changes the page layout by shifting the page content up. If you show any other custom MessageBox in this state, you will see the background of the page in the SystemTray rather than seeing the PhoneChromeBrush resource color. To account for this, We need to detect if the tray has an opacity. If it does, add a large margin to the top.

privatevoid Insert()

{

// Make an assumption that this is within a phone application that is developed "normally"

When the new Nokia Imaging SDK was released I was really excited to start using it within one of my apps. Unlike most, I was not interested in the image filters that change how it looks. I was initially interested in using the resize and crop functionality it had. The day after it was released my wife had surgery, so I had a good amount of time to play with the SDK while I sat in the waiting room. What I wanted to accomplish that was to take a random photo from the users phone, crop and resize it to fit the device and set it as the lockscreen. I know that you can set any image to be the lockscreen and if the image is too big, it will center the image. I needed to do it manually because I wanted to overlay information on the image.

Getting the random image is pretty easy. We’ll just get one from the MediaLibrary.

private Picture GetRandomImage()

{

var rand = new Random(DateTime.Now.Millisecond);

MediaLibrary library = new MediaLibrary();

var album = library.RootPictureAlbum;

int albumIndex = rand.Next(0, album.Albums.Count - 1);

album = album.Albums[albumIndex];

var pictureIndex = rand.Next(0, album.Pictures.Count - 1);

var picture = album.Pictures[pictureIndex];

return picture;

}

Now that we have a Picture, we need to crop and resize it. All actions with an image are done through an EditingSession. You create an EditingSession with the EditingSessionFactory. The EditingSession has two key methods that allow us to crop and/or resize any image to fit the phone screen. The AddFilter method will allow us to crop the image while the RenderToJpegAsync method will allow us to resize the image. The AddFilter method is bar far the best part of the SDK. It allows you to do anything to the image., and I do mean anything. The method takes an IFilter as an argument. Lucky for us you can create a cropping filter. To create a cropping filter, you need to specify an area that will be the crop.

/// <summary>

/// Returns the area needed to crop an image to the desired height and width.

Again, the CropPicture method is generic, allowing for any size. This method could easily be an extension method on the Picture. Now we need to wrap everything up by calling these methods with the phone size. There are already examples of getting the resolution of the phone, so I won’t go into that. Now just put the pieces together.

From there you can save the image to disk, and then maybe save it as a lockscreen. While this code works great, do not expect it to work in a background task. Here is the one place where the imaging SDK falls short. I was wanting to use the SDK in a background task. Background tasks are limited on the amount of resources allowed. The biggest limitation is the memory constraint. Working with images is very memory intensive, especially in C#. So when trying to manipulate an image in a background task, you can quickly run out of memory. I was hoping the imaging SDK would help alleviate some of these issues by working with images smarter. Instead of reading in every pixel of the image and then processing it, it should read n rows of pixels from the stream and then process those rows. This is a hard thing to accomplish, but I’m hoping the awesome people at Nokia can update their SDK to allow for this.

There has been a lot of information flying around about ads in apps these days. Microsoft recently updated PubCenter reporting to include fill rates and number of requests for ads. Dvlup recently partnered with AdDuplex to in its reward program. With all of this hype, I thought I would talk about a common problem with placing ads in apps. That issue is keeping ads in the same location when rotating the phone. Most apps are Portrait apps and display ads either at the top or bottom of the app.

This style works really well for most apps, but what happens when you are displaying data that goes off of the screen? You could either say “Oh well”, you could wrap the text, or you could allow the user to rotate the phone so they can see more. Allowing the content of the page to display in Landscape is as simple as setting SupportedOrientations of the page to PortraitOrLandscape. Doing so allows the user to see more content, but has a side effect of the ad control taking up a lot of room at the bottom of the page.

When supporting Landscape, you really want the ads to stay stationary.

To solve this we’ll create a new Panel like control that will replace the “LayoutRoot” Grid of the standard page. I recently discovered that in two years of blogging I have yet to talk about creating a custom control. We’ll solve this problem by doing just that! A custom control is a control that is not derived from UserControl. Custom controls have a lot of benefits. My top two benefits are reusability and templating (ability to restyle the control). For this we’ll need to create a new ContentControl. A ContentControl allows for a single child to be placed within the xaml element or set from the Content property.

We’ll start by creating two files, one for code and one for xaml. Create a folder named StationaryAdPanel. In the folder add a new code file names StationaryAdPanel.cs and one code file named StationaryAdPanel.theme.xaml.

In the cs file, start defining the control.

publicclass StationaryAdPanel : ContentControl

{

public StationaryAdPanel()

{

DefaultStyleKey = typeof(StationaryAdPanel);

}

}

The constructor defines a DefaultStyleKey. This is the style that defines how the control looks. The style for the control needs to have a simple grid that will allow the ads to be moved to the sides that it needs to be on. Within the file add the following xaml that will define the layout of our control.

Next we’ll define the code for the control. The first step is to override the OnApplyTemplate. This is the method that we use to subscribe to any control events, or just get a control to use later. To keep the ads stationary, we’ll need to listen to when the Orientation of the page changes.

OnOrientationChanged(_page, new OrientationChangedEventArgs(_page.Orientation));

}

}

}

The difficult part about keeping the ad stationary when in landscape is that we will need to rotate it. The downside to rotation is that other controls around the rotated control to not adjust for the rotation. This is solved with controls like the LayoutTransformer from Telerik or by porting the LayoutTransformer from the Silverlight toolkit. However, using these controls requires a dependency on a third party library that we may not want. To overcome this we will ne to adjust for the rotation ourselves. We’ll handle this within the OnOrientationChanged event handler.

When writing custom controls, you need to define a “Generic.xaml” file located in a Themes folder in the root of the project. This is a requirement for custom controls. Nice file can contain the xaml style directly (the template we defined above) or it can reference the xaml files used to define the templates. I prefer to put the styles and templates in separate files rather than flood the Generic.xaml file. To start, create a folder named “Themes” in the root of the project. Right click the folder and add a new code file named “Generic.xaml”. In the file paste the following code (changing YOUR_PROJECT_NAME with the name of the project).

In a previous post we created a behavior that would capitalize any text. This Behavior served a great purpose allowing you to capitalize the text for any TextBlock. What happens when you need to lower case the text? You could create a second Behavior for this, or we could modify the Behavior so that it allows for multiple options. The first option just seems silly when we can reuse code, but how can we specify which text case we want to apply?

In the previous post I talked about some reasons why I like behaviors. One reason I did not list is that you can add Dependency Properties to them. Dependency Properties allow us to set properties in xaml or even better bind to other properties. You can add Dependency Properties to value converters, but that requires your value converter to inherit from DependencyObject. A Behavior already is a DependencyObject!

We’ll start with the ToUpperBehavior from before. We’ll first change the name to ChangeCaseBehavior and we’ll create an enum that will specify what case style we want to change to

publicclass ChangeCaseBehavior : Behavior<TextBlock>

{

...

}

publicenum TextCase

{

Upper,

Lower,

Title

}

This example will show three styles of text casing. I’ll leave it up to you to add others like camelCase or PascalCase. In our previous Behavior, we called ToUpper on the Text of the TextBlock, now we’ll want to respond to the different possibilities for TextCase. We can accomplish this with a simple switch statement within the UpdateText method

privatevoid UpdateText()

{

if (AssociatedObject == null) return;

if (string.IsNullOrEmpty(AssociatedObject.Text)) return;

switch (TextCase)

{

case TextCase.Upper:

AssociatedObject.Text = AssociatedObject.Text.ToUpper();

break;

case TextCase.Lower:

AssociatedObject.Text = AssociatedObject.Text.ToLower();

break;

case TextCase.Title:

char[] text = AssociatedObject.Text.ToCharArray();

// always upper case the first letter

bool shouldUpper = true;

for (int i = 0; i < text.Length; i++)

{

text[i] = shouldUpper

? Char.ToUpper(text[i])

: Char.ToLower(text[i]);

// next letter should be upper case if this is a space

shouldUpper = text[i] == ' ';

}

AssociatedObject.Text = newstring(text);

break;

default:

thrownew ArgumentOutOfRangeException();

}

AssociatedObject.LayoutUpdated -= AssociatedObjectOnLayoutUpdated;

}

Next, we’ll want the ability to set which text casing we want. To do this we’ll add a dependency property to the behavior and respond to the changing of the value.

public TextCase TextCase

{

get { return (TextCase)GetValue(TextCaseProperty); }

set { SetValue(TextCaseProperty, value); }

}

// Using a DependencyProperty as the backing store for TextCase. This enables animation, styling, binding, etc...

I’ve often wondered why the ListPicker in the Windows Phone Toolkit does not have an Opened or Closed event, especially since the SelectionChanged event fires only when the selection changes (as it should). So how are you suppose to know when the ListPicker opens or closes. After all, the ComboBox control has DropDownOpened and DropDownClosed. But then I thought, “Do you really need those? You can always use the IsDropDownOpened property.” The ListPicker does not have an Opened or Closed event and it does not have an IsDropDownOpened property. What the ListPicker does have, is the ListPickerMode property.

//

// Summary:

// Gets or sets the ListPickerMode (ex: Normal/Expanded/Full).

public ListPickerMode ListPickerMode { get; }

This property is actually a DependencyProperty that we can bind to! Let’s say you need to change the visibility of another control when the ListPicker opens/closes. Or maybe you need to change some text based on the picker being opened. We can use the Expression SDK to change values within xaml. For this example we’ll look at changing text based on the picker being opened. We have the following xaml defined.

<StackPanel>

<TextBlockText="Closed"Style="{StaticResource PhoneTextLargeStyle}"/>

<toolkit:ListPickerx:Name="Picker">

<sys:String>Option one</sys:String>

<sys:String>Option two</sys:String>

<sys:String>Option three</sys:String>

<sys:String>Option four</sys:String>

</toolkit:ListPicker>

</StackPanel>

With the above xaml, we will always show “Closed”. Let’s start using the Expression SDK. The first step is to add the Microsoft.Expression.Interactions and System.Windows.Interactivity references to your project.

Next we need to add a DataTrigger to the TextBlock. The DataTrigger will respond to the ListPickerMode property changing and then change the text of the TextBlock.