Dynamic Live Tiles in Windows Phone 7

September 30, 2011

17 comments

One of the attractive features of Windows Phone 7 is the tiles in the start menu. It’s pretty easy to point the main application tile (and secondary tiles) to static URLs. It’s a bit more difficult to create a dynamic image for a live tile.

Starting with tiles

The easiest way to start is by tweaking the WMManifest.xml file (or even easier, but less flexible) the Project Properties Application Tab:

image

The title appears as text under the background image. Ideally, the image should be 173×173 pixels in size. Otherwise, WP7 will stretch/crop as appropriate. The image must be a PNG or JPG file. Using a transparent PNG will make the phone’s accent color show through. Here’s an example with an alternate image (viewed with the emulator):

image

The manifest file contains more options than the above Properties section. This is how it looks now:

<TemplateType5>
  <BackgroundImageURI IsRelative="true" IsResource="false">note.png</BackgroundImageURI>
  <Count>0</Count>
  <Title>Quick Notes</Title
>
</
TemplateType5
>

This is located in the lower part of the file. The Count element allows placing some number between 1 and 99 in the top right corner of the icon. Here’s how it looks when set to the  number 5:

image

This may come in handy.

The new Mango version adds the ability to have a background tile as well, flipping every couple of seconds or so:

<TemplateType5>
  <BackgroundImageURI IsRelative="true" IsResource="false">note.png</BackgroundImageURI>
  <Count>5</Count>
  <Title>Quick Notes</Title>
  <!–<BackBackgroundImageUri IsRelative="true" IsResource="false">background.jpg</BackBackgroundImageUri>–>
  <BackTitle>Back Title</BackTitle>
  <BackContent>Some content</BackContent
>
</
TemplateType5
>

Here’s how the back tile looks:

image

Although there is a BackBacgroundImageUri, it doesn’t seem to work from the XML (but can be set in code).

Changing a Tile Programmatically

This is fine if all we want is something that does not change. To update a tile, however, or to create secondary tiles, we need some code.

Let’s create a quick notes application that allows adding notes that may be pinned to the start menu. The main tile would indicate the number of existing notes.

Updating the main tile can be done like so:

var mainTile = ShellTile.ActiveTiles.First();
mainTile.Update(new StandardTileData {
    Count = _notes.Count
});

The ShellTile class is the main gateway to tiles. The ActiveTiles static collection is a list of all application tiles. The list includes at least the main tile (always the first tile), even if it’s not actually pinned.

To update the tile, we create a StandardTileData object and fill in the required properties. In this case, only the Count is changed, but any other property (such as Title and BackgroundImage can be changed).

Creating new tiles

How about creating new tiles? Essentially it’s not too difficult: fill in a StandardTileData object and call Shelltile.Create:

var data = new StandardTileData {
    Title = note.Name,
    BackTitle = note.Name,
    BackContent = note.BackText,
};
ShellTile.Create(new Uri("/NoteData.xaml?name=" + data.Title, UriKind.Relative), data);

The first argument to Create is a URI that would be followed if the user clicks on the tile. In this case, I’m forwarding this to a XAML page in the app, that would use the query string to display the full note information.

What about the image of the tile? if it’s a predefined image (either within the app or on some server reachable by HTTP), then it’s easy – just set the BackgroundImage property to the appropriate URI. But what about something more dynamic?

Suppose we want the main note text to be displayed in the main tile area (as an image). How could we construct that?

There are 2 steps involved:

1. Create a dynamic image

2. Provide some URI that can reach it

The BackgroundImage property is a URI. I would have expected an ImageSource-derived object, but alas, that is not the case. We have to use a URI somehow.

We’ll use the WriteableBitmap class to create a dynamic image consisting of the note text. One of WriteableBitmap’s abilities is to render any UIElement inside it, so we’re practically not limited to anything.

First, we’ll create a user control that would host our content. Then we’ll render its contents into a WriteableBitmap. Here’s a simple user control markup suitable for our purposes:

UserControl x:Class="QuickNotes.DynamicNote"
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
   xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
   mc:Ignorable="d"
   FontFamily="{StaticResource PhoneFontFamilyNormal}"
   FontSize="{StaticResource PhoneFontSizeNormal}"
   Foreground="{StaticResource PhoneForegroundBrush}"
   d:DesignHeight="173" d:DesignWidth="173" x:Name="ctl" Width="173" Height="140"
            >
    <Border Background="{StaticResource PhoneAccentBrush}">
        <TextBlock x:Name="_text" Margin="6" Width="173" Height="140" Padding="4" HorizontalAlignment="Center"
                  TextWrapping="Wrap" VerticalAlignment="Center" />
    </Border
>
</
UserControl
>

This is essentially a simple TextBlock enclosed in a border, that is colored with the user’s theme (PhoneAccentBrush resource key).

Now let’s draw that into a bitmap:

var ctl = new DynamicNote(note.Text);
ctl.Measure(new Size(173, 173));
ctl.Arrange(new Rect(0, 0, 173, 173));
var bmp = new WriteableBitmap(173, 173);
bmp.Render(ctl, null);
bmp.Invalidate();

Note that we need to call Measure and Arrange if the element to render is not part of a visual tree. Failing to do so will produce unpredictable results (try it!).

The next step is to somehow transform that into a URI. To do that, we’ll save this bitmap to isolated storage (the storage every application has) in a special folder named Shared/ShellContent and create a URI from that:

var iss = IsolatedStorageFile.GetUserStoreForApplication();
var filename = "/Shared/ShellContent/note" + note.Name + ".jpg";
using(var stm = iss.CreateFile(filename)) {
    bmp.SaveJpeg(stm, 173, 173, 0, 80);
}
// pin
var data = new StandardTileData {
    Title = note.Name,
    Count = null,
    BackTitle = note.Name,
    BackContent = note.BackText,
    BackBackgroundImage = new Uri("note.png", UriKind.Relative),
    BackgroundImage = new Uri("isostore:" + filename, UriKind.Absolute)
};
ShellTile.Create(new Uri("/NoteData.xaml?name=" + data.Title, UriKind.Relative), data);

The SaveJpeg is an extension method for WriteableBitmap. It certainly comes in handy in this case. Note the new image URI starting with the “isostore:” prefix.

That’s it. We have a dynamic live tile (lower left):

image

Deleting (unpinning) a tile

To delete (unpin) a tile programmatically, just call the ShellTile.Delete instance method. Here’s an example:

var tile = ShellTile.ActiveTiles.Single(t => t.NavigationUri.ToString().Contains("?" + note.Name + "="));
tile.Delete();

We first must find the tile we want to remove using some properties we’re aware of (typically the NavigationUri property). Then the single call to Delete is all it takes to get rid of the tile.

Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*

17 comments

  1. JohnNovember 2, 2011 ב 21:56

    Great post!
    Unfortunately I don’t know how to add this to my Scheduled task. In this task I use a httpwebrequest to download this and there I also update the live tile’s title.

    Would be great if you could share with us how to add this example to a scheduled task. Where to add the UserControl, I have no XAML code in my ScheduledTaskAgent project?

    Thanks in advance.

    Reply
  2. RazorJune 13, 2012 ב 22:55

    This doesn;t seem to work when you have two tiles. What happens is one disappears when you update the other one. I’m using two different images with two different file names. Its like you can only update one doing it this way

    Reply
  3. icon-designSeptember 13, 2012 ב 11:03

    Excuse for that I interfere … To me this situation is familiar. I invite to discussion. Write here or in PM.

    P.S. Please review our icons for Windows and windows12icons.

    Reply
  4. icon designSeptember 14, 2012 ב 11:31

    Certainly. I join told all above. We can communicate on this theme. Here or in PM.

    P.S. Please review our icons for Windows and windows12icons.

    Reply
  5. icon designSeptember 14, 2012 ב 13:14

    In it something is. Earlier I thought differently, many thanks for the help in this question.

    P.S. Please review our icons for Windows and windows12icons.

    Reply
  6. icon designSeptember 15, 2012 ב 04:40

    This variant does not approach me. Who else, what can prompt?

    P.S. Please review our icons for Windows and windows12iconz.

    Reply
  7. icon designSeptember 15, 2012 ב 07:33

    Yes, reall.y I join told all above. We can communicate on this theme.

    P.S. Please review our icons for Windows and windows12icons.

    Reply
  8. icon designSeptember 15, 2012 ב 10:20

    In my opinion you are not right. I am assured. Let’s discuss. Write to me in PM.

    P.S. Please review our icons for Windows and windows12icons.

    Reply
  9. icon designSeptember 15, 2012 ב 11:26

    On your place I would ask the help for users of this forum.

    P.S. Please review our icons for Windows and windows12icons.

    Reply
  10. icon designSeptember 15, 2012 ב 12:33

    You commit an error. Let’s discuss. Write to me in PM.

    P.S. Please review our icons for Windows and windows12icons.

    Reply
  11. icon designSeptember 15, 2012 ב 13:39

    There are also other lacks

    P.S. Please review our icons for Windows and windows12icons.

    Reply
  12. RosarioJanuary 13, 2013 ב 01:49

    Can I just say what a relief to discover someone who actually understands what they are talking about on
    the web. You actually know how to bring a problem to
    light and make it important. More and more people need to check this out and understand this side of the story.
    I was surprised that you are not more popular since you certainly have the
    gift.

    Reply
  13. FiskJanuary 16, 2013 ב 09:21

    Stability is an additional thing to think about.

    If you plan to purchase bedding stuff individually guarantee these are suitable for the
    newborn and fit properly in the set. All small babies also
    seem more at home in a confined space then in a
    large, airy crib.

    Reply
  14. expazyfleennaMay 4, 2013 ב 06:06

    Whether you are in the market for party favors, a wedding shower gift, wine bag, new baby keepsake, holiday gift or just something fun for yourself, you’re bound to find it here.
    Our felt product line and bar soaps are available in assorted holiday themes and colors.
    I’m adding new products all the time so if there’s something you’re looking for and you don’t see it, email me. I may be able to get it for you!
    other news:
    other news

    Reply
  15. xmclqofh@gmail.comAugust 13, 2013 ב 10:38

    An example of that is a guy named Jerry. His girlfriend Tina tried to cause him to only at her. It worked for some time. He was dating only her for approximately half a year. Next the sex plus the passion not survived inside their relationship, as it does in every relationship. However, Jerry was at ease with her, so he couldn’t breakup along with her. Jerry always liked speaking to a woman Samantha in the office. As things with Tina started failing, Jerry started speaking to Samantha more. He merely wanted to experience the passion again. Eventually, he soon began cheating with Samantha. He couldn’t control his drive. He tried to be exclusive often times, but anytime he appeared finding another woman. He could be terrified of a relationship.

    Reply
  16. uuyito@gmail.comAugust 22, 2013 ב 08:26

    Actor Brooke Shields noted in the book “Down Came the Rain : My Discover Postpartum Depression” that whenever PMS made her “introspective or melancholy or when the pressures of life forced me to be gloomy, I knew this sense wouldn’t last forever. However was sadness of the shockingly different magnitude. It felt like it might last a lifetime.”.

    Reply
  17. dknfccnx@gmail.comAugust 24, 2013 ב 20:22

    We might also consider combining this therapy with many other interventions to supply a greater advantage to patients suffering from heart failure.”Dr. Its mission is usually to advocate for quality cardiovascular care through education, research, promotion, development and employing standards and guidelines and to influence health-related policy. ACC.07 and also i2 Summit is a largest cardiovascular meeting, combining cardiologists and cardiovascular specialists to show the fresh new discoveries in treatment and prevention, while raising the ACC achieve its mission to address and improve issues in cardiovascular medicine..

    Reply