首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

Windows 8 磚通知完整指南:模板、佇列、次要磚與排程更新

     編輯:關於.NET

前言

磚是 Windows 8 啟動畫面的核心元素,透過豐富的模板、通知佇列、次要磚與排程更新機制,應用程式能在使用者未開啟應用時也能傳遞即時資訊。本文將系統性介紹 Tile 的 46 種模板、通知佇列運作、Secondary Tile 建立與更新、以及排程與輪詢更新的實作方式。

一、展示全部 46 種 Tile 模板

系統提供 46 種預定義模板,涵蓋方塊與寬幅尺寸、純文字、圖文混合等樣式。以下範例透過掃描專案內的示範圖片,以 GridView 呈現所有模板外觀。

XAML 介面

<Page x:Class="XamlDemo.Notification.Tile.AllTemplates" xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:XamlDemo.Notification.Tile" xmlns:d="https://schemas.microsoft.com/expression/blend/2008" xmlns:mc="https://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d">
<Grid Background="Transparent">
<Grid.Resources>
<Style x:Key="ItemTitleStyle" TargetType="TextBlock">
<Setter Property="FontSize" Value="14.667"/>
</Style>
<ItemsPanelTemplate x:Key="StoreFrontGridItemsPanelTemplate">
<WrapGrid MaximumRowsOrColumns="3" VerticalChildrenAlignment="Top" HorizontalChildrenAlignment="Left"/>
</ItemsPanelTemplate>
<Style x:Key="StoreFrontTileStyle" TargetType="GridViewItem">
<Setter Property="FontFamily" Value="Segoe UI" />
<Setter Property="Height" Value="300" />
<Setter Property="Width" Value="260" />
<Setter Property="Padding" Value="0" />
<Setter Property="Margin" Value="0" />
<Setter Property="HorizontalContentAlignment" Value="Left" />
<Setter Property="VerticalContentAlignment" Value="Top" />
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="TabNavigation" Value="Local" />
</Style>
<DataTemplate x:Key="StoreFrontTileTemplate">
<Grid HorizontalAlignment="Left" Background="Transparent">
<StackPanel Orientation="Vertical">
<TextBlock TextWrapping="Wrap" VerticalAlignment="Center" Text="{Binding FileName}" HorizontalAlignment="Left" />
<Image Source="{Binding Path}" Stretch="None" VerticalAlignment="Center" HorizontalAlignment="Left" Margin="0,10,0,0"/>
</StackPanel>
</Grid>
</DataTemplate>
</Grid.Resources>
<GridView x:Name="gridView" Margin="120 0 0 0" ItemTemplate="{StaticResource StoreFrontTileTemplate}" ItemContainerStyle="{StaticResource StoreFrontTileStyle}" ItemsPanel="{StaticResource StoreFrontGridItemsPanelTemplate}" BorderBrush="LightGray" VerticalAlignment="Top" ScrollViewer.VerticalScrollBarVisibility="Auto" ScrollViewer.HorizontalScrollBarVisibility="Auto" SelectionMode="None" />
</Grid>
</Page>

程式碼後置

using System;
using System.Linq;
using Windows.ApplicationModel;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;

namespace XamlDemo.Notification.Tile
{
    public sealed partial class AllTemplates : Page
    {
        public AllTemplates()
        {
            this.InitializeComponent();
        }

        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            var folder = await Package.Current.InstalledLocation.GetFolderAsync(@"Notification\Tile\TemplateDemo");
            var files = await folder.GetFilesAsync();
            var dataSource = from p in files
                             select new { FileName = p.DisplayName, Path = "ms-appx:///Notification/Tile/TemplateDemo/" + p.Name };
            gridView.ItemsSource = dataSource;
        }
    }
}

二、Tile 通知佇列:循環顯示最多 5 則通知

啟用 EnableNotificationQueue(true) 後,磚可循環顯示最多 5 個不同的 TileNotification,依先進先出原則維護。每則通知需指定唯一的 Tag 作為識別碼。

XAML 介面

<Page x:Class="XamlDemo.Notification.Tile.Queue" xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:XamlDemo.Notification.Tile" xmlns:d="https://schemas.microsoft.com/expression/blend/2008" xmlns:mc="https://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d">
<Grid Background="Transparent">
<StackPanel Margin="120 0 0 0">
<TextBox Name="lblMsg" Height="100" TextWrapping="Wrap" AcceptsReturn="True" FontSize="14.667" Margin="0 0 10 0" />
<Button Name="btnSendNewTile" Content="發送一個新的 Tile 通知" Click="btnSendNewTile_Click_1" Margin="0 10 0 0" />
</StackPanel>
</Grid>
</Page>

程式碼後置

using NotificationsExtensions.TileContent;
using System;
using Windows.UI.Notifications;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;

namespace XamlDemo.Notification.Tile
{
    public sealed partial class Queue : Page
    {
        public Queue()
        {
            this.InitializeComponent();
        }

        private void btnSendNewTile_Click_1(object sender, RoutedEventArgs e)
        {
            string randomString = new Random().Next(1000, 10000).ToString();
            ITileSquareText04 squareTileContent = TileContentFactory.CreateTileSquareText04();
            squareTileContent.TextBodyWrap.Text = randomString;
            ITileWideText03 tileContent = TileContentFactory.CreateTileWideText03();
            tileContent.TextHeadingWrap.Text = randomString;
            tileContent.SquareContent = squareTileContent;
            string tag = randomString;
            TileNotification tileNotification = tileContent.CreateNotification();
            tileNotification.Tag = tag;
            TileUpdater tileUpdater = TileUpdateManager.CreateTileUpdaterForApplication();
            tileUpdater.EnableNotificationQueue(true);
            tileUpdater.Update(tileNotification);
            lblMsg.Text = "Tag: " + tag;
            lblMsg.Text += Environment.NewLine;
            lblMsg.Text += tileContent.GetContent();
        }
    }
}

三、Secondary Tile:一個應用程式擁有多個磚

透過 SecondaryTile 類別,可將特定內容釘選到啟動畫面,每個次要磚擁有獨立的 TileId、引數、標題、Logo 等屬性。使用者點擊次要磚啟動應用時,可在 App.xaml.cs 的 OnLaunched 中透過 args.TileId 與 args.Arguments 判斷進入點。

主要操作

  • 釘選:RequestCreateForSelectionAsync 彈出確認對話框。
  • 更新磚屬性:建立新的 SecondaryTile(tileId) 實例修改屬性後呼叫 UpdateAsync。
  • 更新磚通知:使用 TileUpdateManager.CreateTileUpdaterForApplication(tileId) 取得對應的 TileUpdater。
  • 移除:RequestDeleteForSelectionAsync。
  • 查詢:SecondaryTile.FindAllAsync() 取得所有次要磚清單。

XAML 介面

<Page x:Class="XamlDemo.Notification.Tile.MultipleTiles" xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:XamlDemo.Notification.Tile" xmlns:d="https://schemas.microsoft.com/expression/blend/2008" xmlns:mc="https://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d">
<Grid Background="Transparent">
<StackPanel Margin="120 0 0 0">
<TextBlock Name="lblMsg" FontSize="14.667" />
<Button Name="btnPinSecondaryTile" Content="釘選一個新的 SecondaryTile" Click="btnPinSecondaryTile_Click_1" Margin="0 10 0 0" />
<Button Name="btnUpdateAllSecondaryTiles" Content="更新全部 SecondaryTile(不包含主 Tile)" Click="btnUpdateAllSecondaryTiles_Click_1" Margin="0 10 0 0" />
<Button Name="btnUpdateAllSecondaryTilesNotification" Content="更新全部 SecondaryTile 的 Tile 通知(不包含主 Tile)" Click="btnUpdateAllSecondaryTilesNotification_Click_1" Margin="0 10 0 0" />
<Button Name="btnClearAllSecondaryTiles" Content="清除全部 SecondaryTile(不包含主 Tile)" Click="btnClearAllSecondaryTiles_Click_1" Margin="0 10 0 0" />
</StackPanel>
</Grid>
</Page>

程式碼後置

using NotificationsExtensions.TileContent;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Windows.UI.Notifications;
using Windows.UI.Popups;
using Windows.UI.StartScreen;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using XamlDemo.Common;

namespace XamlDemo.Notification.Tile
{
    public sealed partial class MultipleTiles : Page
    {
        public MultipleTiles()
        {
            this.InitializeComponent();
        }

        private async void btnPinSecondaryTile_Click_1(object sender, RoutedEventArgs e)
        {
            Uri logo = new Uri("ms-appx:///Assets/Logo.png");
            Uri wideLogo = new Uri("ms-appx:///Assets/WideLogo.png");
            Uri smallLogo = new Uri("ms-appx:///Assets/SmallLogo.png");
            string tileId = new Random().Next(1000, 10000).ToString();
            SecondaryTile secondaryTile = new SecondaryTile(
                tileId,
                "ShortName",
                "DisplayName",
                "Arguments(TileId: " + tileId + ")",
                TileOptions.ShowNameOnLogo | TileOptions.ShowNameOnWideLogo | TileOptions.CopyOnDeployment,
                logo);
            secondaryTile.ForegroundText = ForegroundText.Light;
            secondaryTile.SmallLogo = smallLogo;
            secondaryTile.WideLogo = wideLogo;
            bool isPinned = await secondaryTile.RequestCreateForSelectionAsync(Helper.GetElementRect((FrameworkElement)sender), Placement.Below);
            await ShowAllTilesForApplication();
        }

        private async void btnUpdateAllSecondaryTiles_Click_1(object sender, RoutedEventArgs e)
        {
            IReadOnlyList<SecondaryTile> tileList = await SecondaryTile.FindAllAsync();
            foreach (SecondaryTile tile in tileList)
            {
                SecondaryTile secondaryTile = new SecondaryTile(tile.TileId);
                secondaryTile.WideLogo = new Uri("ms-appx:///Assets/Logo.png");
                secondaryTile.Arguments = "Updated Arguments(TileId: " + tile.TileId + ")";
                bool success = await secondaryTile.UpdateAsync();
            }
        }

        private async void btnUpdateAllSecondaryTilesNotification_Click_1(object sender, RoutedEventArgs e)
        {
            IReadOnlyList<SecondaryTile> tileList = await SecondaryTile.FindAllAsync();
            foreach (var tile in tileList)
            {
                ITileWideText04 tileContent = TileContentFactory.CreateTileWideText04();
                tileContent.TextBodyWrap.Text = "hi webabcd";
                ITileSquareText04 squareContent = TileContentFactory.CreateTileSquareText04();
                squareContent.TextBodyWrap.Text = "hi webabcd";
                tileContent.SquareContent = squareContent;
                TileNotification tileNotification = tileContent.CreateNotification();
                TileUpdater tileUpdater = TileUpdateManager.CreateTileUpdaterForApplication(tile.TileId);
                tileUpdater.Update(tileNotification);
            }
        }

        private async void btnClearAllSecondaryTiles_Click_1(object sender, RoutedEventArgs e)
        {
            IReadOnlyList<SecondaryTile> tileList = await SecondaryTile.FindAllAsync();
            foreach (var tile in tileList)
            {
                bool isUnpinned = await tile.RequestDeleteForSelectionAsync(Helper.GetElementRect((FrameworkElement)sender), Placement.Below);
            }
            await ShowAllTilesForApplication();
        }

        private async Task ShowAllTilesForApplication()
        {
            IReadOnlyList<SecondaryTile> tileList = await SecondaryTile.FindAllAsync();
            lblMsg.Text += "此 app 的全部 SecondaryTile 的 tileId 列表: ";
            foreach (var tile in tileList)
            {
                lblMsg.Text += tile.TileId + " ";
            }
        }
    }
}

App.xaml.cs 處理啟動引數

protected async override void OnLaunched(LaunchActivatedEventArgs args)
{
    if (args.TileId != "Win8App")
    {
        await new Windows.UI.Popups.MessageDialog(args.Arguments).ShowAsync();
    }
}

四、排程磚通知與輪詢更新

ScheduledTileNotification 允許指定未來特定時間顯示磚通知,支援 Id、Tag、ExpirationTime 等屬性。輪詢更新 則透過 StartPeriodicUpdate 定期從伺服器抓取 XML 內容更新磚,支援多個 URI 循環顯示,週期可設為 30 分鐘、1 小時、6 小時、12 小時或每日。

XAML 介面

<Page x:Class="XamlDemo.Notification.Tile.ScheduledTile" xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:XamlDemo.Notification.Tile" xmlns:d="https://schemas.microsoft.com/expression/blend/2008" xmlns:mc="https://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d">
<Grid Background="Transparent">
<StackPanel Margin="120 0 0 0">
<ListBox Name="listBox" Width="800" Height="300" HorizontalAlignment="Left">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding TileId}" VerticalAlignment="Center" />
<TextBlock Text="{Binding Text}" Margin="15 0 0 0" VerticalAlignment="Center" />
<HyperlinkButton Name="btnRemove" Content="刪除此 ScheduledTileNotification" Tag="{Binding TileId}" Margin="15 0 0 0" Click="btnRemove_Click_1" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Button Name="btnScheduledTile" Content="ScheduledTileNotification 的 Demo(15 秒後更新指定的 Tile 通知)" Click="btnScheduledTile_Click_1" Margin="0 10 0 0" />
<Button Name="btnStartPeriodicUpdate" Content="啟動一個「輪詢伺服器,而後更新 Tile」的任務" Click="btnStartPeriodicUpdate_Click_1" Margin="0 10 0 0" />
</StackPanel>
</Grid>
</Page>

程式碼後置

using NotificationsExtensions.TileContent;
using System;
using System.Collections.Generic;
using Windows.UI.Notifications;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;

namespace XamlDemo.Notification.Tile
{
    public sealed partial class ScheduledTile : Page
    {
        public ScheduledTile()
        {
            this.InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            ShowScheduledTiles();
        }

        private void btnScheduledTile_Click_1(object sender, RoutedEventArgs e)
        {
            ITileSquareText04 squareContent = TileContentFactory.CreateTileSquareText04();
            squareContent.TextBodyWrap.Text = "ScheduledTileNotification Demo";
            ITileWideText09 tileContent = TileContentFactory.CreateTileWideText09();
            tileContent.TextHeading.Text = "ScheduledTileNotification Demo";
            tileContent.TextBodyWrap.Text = "received: " + DateTime.Now.ToString("hh:mm:ss");
            tileContent.SquareContent = squareContent;
            ScheduledTileNotification tile = new ScheduledTileNotification(tileContent.GetXml(), DateTime.Now.AddSeconds(15));
            string tileId = new Random().Next(1000, 10000).ToString();
            tile.Id = tileId;
            TileUpdater tileUpdater = TileUpdateManager.CreateTileUpdaterForApplication();
            tileUpdater.AddToSchedule(tile);
            ShowScheduledTiles();
        }

        private void ShowScheduledTiles()
        {
            List<MyScheduledTile> dataSource = new List<MyScheduledTile>();
            TileUpdater tileUpdater = TileUpdateManager.CreateTileUpdaterForApplication();
            IReadOnlyList<ScheduledTileNotification> scheduledTiles = tileUpdater.GetScheduledTileNotifications();
            int tileCount = scheduledTiles.Count;
            for (int i = 0; i < tileCount; i++)
            {
                ScheduledTileNotification tile = scheduledTiles[i];
                dataSource.Add(new MyScheduledTile()
                {
                    TileId = tile.Id,
                    Text = tile.Content.GetElementsByTagName("text")[0].InnerText
                });
            }
            listBox.ItemsSource = dataSource;
        }

        private void btnRemove_Click_1(object sender, RoutedEventArgs e)
        {
            string tileId = (string)(sender as FrameworkElement).Tag;
            TileUpdater tileUpdater = TileUpdateManager.CreateTileUpdaterForApplication();
            IReadOnlyList<ScheduledTileNotification> scheduledTiles = tileUpdater.GetScheduledTileNotifications();
            int tileCount = scheduledTiles.Count;
            for (int i = 0; i < tileCount; i++)
            {
                if (scheduledTiles[i].Id == tileId)
                {
                    tileUpdater.RemoveFromSchedule(scheduledTiles[i]);
                    ShowScheduledTiles();
                    break;
                }
            }
        }

        class MyScheduledTile
        {
            public string TileId { get; set; }
            public string Text { get; set; }
        }

        private void btnStartPeriodicUpdate_Click_1(object sender, RoutedEventArgs e)
        {
            TileUpdater tileUpdater = TileUpdateManager.CreateTileUpdaterForApplication();
            tileUpdater.StartPeriodicUpdate(new Uri("https://localhost:39629/TileContent.xml", UriKind.Absolute), PeriodicUpdateRecurrence.HalfHour);
        }
    }
}

總結

  • 掌握 46 種模板是設計豐富磚內容的基礎。
  • 通知佇列讓單一磚能輪播多則資訊,提升資訊密度。
  • Secondary Tile 為特定內容提供獨立進入點,增強應用程式可發現性。
  • 排程與輪詢更新機制讓磚內容保持即時性,無需應用程式常駐執行。

[原始碼下載]:https://files.cnblogs.com/webabcd/Windows8.rar

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved