Wednesday 18 March 2015

Pin to Home Screen

winRt Apps can "Bookmark" a page within your app to your home screen or start screen (whatever you want to call it), It's actually pretty straight forward how to do this.

what we'll need to do is from some sort of command is we'll have to create a SecondaryTile. This secondary tile is going to require four things

  • TileId (unique string)
  • Arguments (App specific arguments to pass to your app when the tile is activate to let your app know what to do once it starts)
  • DisplayName (the name )
  • Tile Icon the image the tile will show

with those four set

var sc = new SecondaryTile
{  
    TileId = TileId,
    Arguments = Arguments,
    DisplayName = DisplayName
};
sc.VisualElements.Square150x150Logo = new Uri("ms-appx:///Assets/logo.png");

sc.VisualElements.ShowNameOnSquare150x150Logo = true;

all that's left to do is pin it

await sc.RequestCreateAsync()

now what I usually do is create a function in some sort of Helper class or in my case usually an abstract base ViewModel class, the location is moot; what matters is that since you'll most likely be calling this from numerous places in your app you should write a method that handles.

public Action GetPinAction(string TileId, string Arguments, string DisplayName)
{
    return  async () => {
           
        var sc = new SecondaryTile
        {  
            TileId = TileId,
            Arguments = Arguments,
            DisplayName = DisplayName
        };
        sc.VisualElements.Square150x150Logo = new Uri("ms-appx:///Assets/logo.png");
        sc.VisualElements.ShowNameOnSquare150x150Logo = true;

        if (await sc.RequestCreateAsync())
            this.OnPropertyChanged("ShowPinToStart");
    };

}

keep in mind that the level of customization is really up to you, this is just an example, you can implement logic to pass the location of the logo in, different sizes of logos etc. With a function generated to built to return an action you can now just call this whenever you want to add pin logic to a page.

this.PinToStartCommand = new RelayCommand(base.GetPinAction(String.Format("{0}&{1}&{2}", this.RouteName, FromStationId, ToStationId), "Station", this.Title));


Now that we are pinning things to the home/start screen of our device lets create some logic in our app.xaml.cs file to handle launching our app from a secondary tile. Find the OnLaunched method

protected async override void OnLaunched(LaunchActivatedEventArgs e)

In that method use the parameter to create a switch statement to hanlde your various Secondary Tile App launches,

switch(e.Arguments)
{
    case "Route":
        rootFrame.Navigate(typeof(RoutePage), e.TileId);
        break;
    case "Station":
        rootFrame.Navigate(typeof(StationPage), e.TileId);
        break;

}

you can  handle what to do with your data however you please. That's about it