# win10 uwp 活動磁貼
本文翻譯:https://mobileprogrammerblog.wordpress.com/2015/12/23/live-tiles-and-notifications-in-universal-windows-10-app/ 我會寫很多質量很低文章,文章都是胡說,如果看不懂可以發到郵箱
如下面的圖,很多應用都有活動磁貼,活動磁貼就是放在開始菜單,會像是下面圖一樣顯示東西

win10總有很多看起來有用,但實際沒什么卵用的東西,我一點不覺得用戶覺得這個有用,但是我們能做活動磁貼UWP,微軟一直把開發者當成用戶。
<!--more-->
<div id="toc"></div>
做一個UWP當然需要我們打開神器
新建一個項目,空UWP,可以使用快捷鍵`ctrl+shift+N`

我們打開MainPage.xaml,新建的時候有點慢,我們需要等一下如果放在固態基本不用等。

```xml
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<StackPanel Grid.Row="0" Margin="12">
<TextBlock Text="Adaptive Tiles" FontSize="20" FontWeight="Bold" />
<Button Click="UpdateBadge" VerticalAlignment="Top" Margin="12" Background="#330070B0">Update Badge Count</Button>
<Button Click="UpdatePrimaryTile" VerticalAlignment="Top" Background="#330070B0" Margin="12">Update Primary Tile</Button>
</StackPanel>
<StackPanel Grid.Row="1" Margin="12">
<TextBlock Text="Interactive Toast" FontSize="20" FontWeight="Bold" />
<StackPanel Orientation="Horizontal" Margin="12">
<TextBlock x:Name="Description" VerticalAlignment="Center" Text="{x:Bind CurrentToDoTask.Description, Mode=OneWay}" FontWeight="Bold" />
<CheckBox Margin="12,0,0,0" IsChecked="{x:Bind CurrentToDoTask.IsComplete, Mode=OneWay}" IsEnabled="False" />
</StackPanel>
<Button Click="Notify" Background="#330070B0" Margin="12">Notify</Button>
<Button Background="#330070B0" Click="{x:Bind Refresh}" Margin="12">Refresh</Button>
</StackPanel>
</Grid>
<Grid Grid.Row="1">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<StackPanel Grid.Row="0" Margin="12">
<TextBlock Text="我翻譯的 本文來自http://blog.csdn.net/lindexi_gd" />
<TextBlock Text="磁貼" FontSize="20" FontWeight="Bold" />
<Button Click="UpdateBadge" VerticalAlignment="Top" Margin="12" Background="#330070B0">更新磁貼數</Button>
<Button Click="UpdatePrimaryTile" VerticalAlignment="Top" Background="#330070B0" Margin="12">更新顯示磁貼</Button>
</StackPanel>
<StackPanel Grid.Row="1" Margin="12">
<TextBlock Text="互動吐司" FontSize="20" FontWeight="Bold" />
<StackPanel Orientation="Horizontal" Margin="12">
<TextBlock x:Name="xdescription" VerticalAlignment="Center" Text="{x:Bind CurrentToDoTask.Description, Mode=OneWay}" FontWeight="Bold" />
<CheckBox Margin="12,0,0,0" IsChecked="{x:Bind CurrentToDoTask.IsComplete, Mode=OneWay}" IsEnabled="False" />
</StackPanel>
<Button Click="Notify" Background="#330070B0" Margin="12">通知</Button>
<Button Background="#330070B0" Click="{x:Bind Refresh}" Margin="12">更新</Button>
</StackPanel>
</Grid>
</Grid>
```
寫完我們可以看到下面的樣子


上面一張是作者寫的開始我沒有去看,以為他寫出來就是上面那圖,復制了他代碼在我寫博客,發現他的代碼錯了,我自己重新寫,發現我應該弄個中文,就寫了第二張圖,我們看到上面代碼是第二張圖。
我們右擊方案新建一個文件夾`DATA`,里面新建一個類`PrimaryTile`,可以看下面圖

我們在PrimaryTile
```csharp
public class PrimaryTile
{
public string time
{
set;
get;
} = "8:15 AM, Saturday";
public string message
{
set;
get;
} = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore.";
public string message2
{
set;
get;
} = "At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident.";
public string branding
{
set;
get;
} = "name";
public string appName
{
set;
get;
} = "UWP";
}
```

創建一個文件夾`services` 新建`tileservice.cs` `toastservice.cs`
```csharp
public class TileService
{
public static void SetBadgeCountOnTile(int count)
{
// Update the badge on the real tile
System.Xml.XmlDocument badgeXml = BadgeUpdateManager.GetTemplateContent(BadgeTemplateType.BadgeNumber);
XmlElement badgeElement = (XmlElement) badgeXml.SelectSingleNode("/badge");
badgeElement.SetAttribute("value", count.ToString());
BadgeNotification badge = new BadgeNotification(badgeXml);
BadgeUpdateManager.CreateBadgeUpdaterForApplication().Update(badge);
}
public static XmlDocument CreateTiles(PrimaryTile primaryTile)
{
XDocument xDoc = new XDocument(
new XElement("tile", new XAttribute("version", 3),
new XElement("visual",
// Small Tile
new XElement("binding", new XAttribute("branding", primaryTile.branding),
new XAttribute("displayName", primaryTile.appName), new XAttribute("template", "TileSmall"),
new XElement("group",
new XElement("subgroup",
new XElement("text", primaryTile.time, new XAttribute("hint-style", "caption")),
new XElement("text", primaryTile.message,
new XAttribute("hint-style", "captionsubtle"), new XAttribute("hint-wrap", true),
new XAttribute("hint-maxLines", 3))
)
)
),
// Medium Tile
new XElement("binding", new XAttribute("branding", primaryTile.branding),
new XAttribute("displayName", primaryTile.appName), new XAttribute("template", "TileMedium"),
new XElement("group",
new XElement("subgroup",
new XElement("text", primaryTile.time, new XAttribute("hint-style", "caption")),
new XElement("text", primaryTile.message,
new XAttribute("hint-style", "captionsubtle"), new XAttribute("hint-wrap", true),
new XAttribute("hint-maxLines", 3))
)
)
),
// Wide Tile
new XElement("binding", new XAttribute("branding", primaryTile.branding),
new XAttribute("displayName", primaryTile.appName), new XAttribute("template", "TileWide"),
new XElement("group",
new XElement("subgroup",
new XElement("text", primaryTile.time, new XAttribute("hint-style", "caption")),
new XElement("text", primaryTile.message,
new XAttribute("hint-style", "captionsubtle"), new XAttribute("hint-wrap", true),
new XAttribute("hint-maxLines", 3)),
new XElement("text", primaryTile.message2,
new XAttribute("hint-style", "captionsubtle"), new XAttribute("hint-wrap", true),
new XAttribute("hint-maxLines", 3))
),
new XElement("subgroup", new XAttribute("hint-weight", 15),
new XElement("image", new XAttribute("placement", "inline"),
new XAttribute("src", "Assets/StoreLogo.png"))
)
)
),
//Large Tile
new XElement("binding", new XAttribute("branding", primaryTile.branding),
new XAttribute("displayName", primaryTile.appName), new XAttribute("template", "TileLarge"),
new XElement("group",
new XElement("subgroup",
new XElement("text", primaryTile.time, new XAttribute("hint-style", "caption")),
new XElement("text", primaryTile.message,
new XAttribute("hint-style", "captionsubtle"), new XAttribute("hint-wrap", true),
new XAttribute("hint-maxLines", 3)),
new XElement("text", primaryTile.message2,
new XAttribute("hint-style", "captionsubtle"), new XAttribute("hint-wrap", true),
new XAttribute("hint-maxLines", 3))
),
new XElement("subgroup", new XAttribute("hint-weight", 15),
new XElement("image", new XAttribute("placement", "inline"),
new XAttribute("src", "Assets/StoreLogo.png"))
)
)
)
)
)
);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xDoc.ToString());
//Debug.WriteLine(xDoc);
return xmlDoc;
}
}
public static class ToastService
{
public static System.Xml.XmlDocument CreateToast()
{
XDocument xDoc = new XDocument(
new XElement("toast",
new XElement("visual",
new XElement("binding", new XAttribute("template", "ToastGeneric"),
new XElement("text", "To Do List"),
new XElement("text", "Is the task complete?")
) // binding
), // visual
new XElement("actions",
new XElement("action", new XAttribute("activationType", "background"),
new XAttribute("content", "Yes"), new XAttribute("arguments", "yes")),
new XElement("action", new XAttribute("activationType", "background"),
new XAttribute("content", "No"), new XAttribute("arguments", "no"))
) // actions
)
);
System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
xmlDoc.LoadXml(xDoc.ToString());
return xmlDoc;
}
}
```
我們創建文件`ToDoTask.cs` `ToDoTaskFileHelper.cs`

```csharp
public class ToDoTask
{
public string Description
{
get;
set;
}
public Guid Id
{
get;
set;
}
public bool? IsComplete
{
get;
set;
}
public string ToJson()
{
using (MemoryStream stream = new MemoryStream())
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof (ToDoTask));
serializer.WriteObject(stream, this);
stream.Position = 0;
byte[] jsonBytes = stream.ToArray();
return Encoding.UTF8.GetString(jsonBytes, 0, jsonBytes.Length);
}
}
public static ToDoTask FromJson(string json)
{
// note: throws exception if the json is not valid
JsonObject jsonData = JsonObject.Parse(json);
// exceptions will be thrown if the values do not match the types
return new ToDoTask
{
Id = Guid.Parse(jsonData["Id"].GetString()),
Description = jsonData["Description"].GetString(),
IsComplete = jsonData["IsComplete"].GetBoolean()
};
}
}
public static class ToDoTaskFileHelper
{
public static async Task ReadToDoTaskJsonAsync()
{
// declare an empty variable to be filled later
string json = null;
// define where the file resides
StorageFolder localfolder = ApplicationData.Current.LocalFolder;
// see if the file exists
if (await localfolder.TryGetItemAsync(Filename) != null)
{
// open the file
StorageFile textfile = await localfolder.GetFileAsync(Filename);
// read the file
json = await FileIO.ReadTextAsync(textfile);
}
// if the file doesn't exist, we'll copy the app copy to local storage
else
{
StorageFile storageFile =
await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/task.json"));
await storageFile.CopyAsync(ApplicationData.Current.LocalFolder);
json = await FileIO.ReadTextAsync(storageFile);
}
return json;
}
public static async Task SaveToDoTaskJson(string json)
{
StorageFolder localfolder = ApplicationData.Current.LocalFolder;
StorageFile textfile = await localfolder.GetFileAsync(Filename);
await FileIO.WriteTextAsync(textfile, json);
}
private static readonly string Filename = "task.json";
}
```
`task.json`
```csharp
{"Description":"A test task","Id":"9d6c3585-d0c2-4885-8fe0-f02727f8e483","IsComplete":true}
```
我們把剛才寫的MainPage的按鈕綁定到

```csharp
public sealed partial class MainPage : Page, INotifyPropertyChanged
{
public MainPage()
{
InitializeComponent();
Loaded += MainPage_Loaded;
}
#region Delegates
public event PropertyChangedEventHandler PropertyChanged;
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
Refresh();
}
#endregion
public ToDoTask CurrentToDoTask
{
get
{
return _currentToDoTask;
}
set
{
_currentToDoTask = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(CurrentToDoTask)));
}
}
private int _count;
private ToDoTask _currentToDoTask;
private async void Refresh()
{
void json = await ToDoTaskFileHelper.ReadToDoTaskJsonAsync();
CurrentToDoTask = ToDoTask.FromJson(json);
}
private void UpdateBadge(object sender, RoutedEventArgs e)
{
_count++;
TileService.SetBadgeCountOnTile(_count);
}
private void UpdatePrimaryTile(object sender, RoutedEventArgs e)
{
XmlDocument xmlDoc = TileService.CreateTiles(new PrimaryTile());
TileUpdater updater = TileUpdateManager.CreateTileUpdaterForApplication();
TileNotification notification = new TileNotification(xmlDoc);
updater.Update(notification);
}
private void Notify(object sender, RoutedEventArgs e)
{
System.Xml.XmlDocument xmlDoc = ToastService.CreateToast();
ToastNotifier notifier = ToastNotificationManager.CreateToastNotifier();
ToastNotification toast = new ToastNotification(xmlDoc);
notifier.Show(toast);
}
}
```
寫完自己運行就可以知道,更新磁貼,更新界面,提示通知,每個對應的代碼自己可以看到,這個國內很多教程


http://blog.csdn.net/lindexi_gd
https://mobileprogrammerblog.wordpress.com/2015/12/23/live-tiles-and-notifications-in-universal-windows-10-app/
- Introduction
- 控件
- Win10 UWP Intro to controls and events
- win10 UWP Controls by function
- win10 uwp App-to-app communication 應用通信
- win10 UWP 使用MD5算法
- win10 UWP 全屏
- win10 uwp 使用油墨輸入
- 三種方式設置特定設備UWP XAML view
- win10 uwp iot
- win10 uwp 活動磁貼
- win 10 UWP 標簽
- Xamarin Forms 進度條控件
- win10 UWP MessageDialog 和 ContentDialog
- win10 uwp 俄羅斯方塊
- win10 UWP Hmac
- win10 UWP 單元測試
- win10 uwp 判斷文件存在
- win10 UWP 標題欄后退
- win10 uwp 分治法
- win10 UWP 應用設置
- win10 uwp BadgeLogo 顏色
- win10 uwp json
- win10 uwp Window.Current.Dispatcher中Current為null
- win10 uwp 無法附加到CoreCLR
- win10 uwp 自定義控件 SplitViewItem
- win10 uwp ContentDialog 點確定不關閉
- win10 uwp smms圖床
- win10 uwp 從StorageFile獲取文件大小
- win10 uwp 如何讓WebView標識win10手機
- win10 uwp 上傳Nuget
- win10 uwp 手動鎖Bitlocker
- win10 uwp 圓角按鈕
- win10 uwp 入門
- win10 uwp 切換主題
- win10 uwp 隨著數字變化顏色控件
- win10 uwp 設置啟動窗口大小 獲取窗口大小
- win10 uwp 簡單MasterDetail
- win10 uwp 異步進度條
- win10 uwp 訪問解決方案文件
- C# 7.0
- win10 uwp InkCanvas控件數據綁定
- win10 uwp 列表模板選擇器
- win10 uwp 隱藏實時可視化
- win10 uwp 讀取文本ASCII錯誤
- Visual studio 創建項目失敗vstemplate
- Visual Studio 自定義項目模板
- win10 uwp 車表盤 徑向規
- win10 uwp 截圖 獲取屏幕顯示界面保存圖片
- win10 uwp 獲得焦點改變
- win10 uwp 應用轉后臺清理內存
- win10 uwp 隱私聲明
- win10 uwp 打包第三方字體到應用
- win10 uwp 九幽圖床
- win10 uwp 興趣線
- win10 uwp 右擊浮出窗在點擊位置
- win10 uwp 保存用戶選擇文件夾
- win10 uwp 打電話
- visual studio 2015 warning MSB3246
- win10 uwp 繪圖 Line 控件使用
- win10 uwp 存放網絡圖片到本地
- win10 uwp 判斷本地ip
- win10 uwp 彈起鍵盤不隱藏界面元素
- win10 uwp Markdown
- C# 設計模式 責任鏈
- win10 uwp 顯示SVG
- win10 uwp 網絡編程
- win10 uwp HttpClient post錯誤
- win10 uwp win2d
- win10 uwp 布局
- win10 uwp 初始屏幕
- win10 uwp dataGrid
- win10 uwp 魔力鬼畜
- win10 uwp如何使用DataTemplate
- win10 uwp 多語言
- win10 uwp CSDN閱讀 源代碼
- win10 uwp 語音
- win10 uwp 動畫
- win10 uwp 顏色轉換
- win10 uwp 獲得Slider拖動結束的值
- Windows 10「設置」應用完整MS-Settings快捷方式匯總
- win10 uwp 用廣告賺錢
- win10 uwp 快捷鍵
- win10 UWP MvvmLight入門
- win10 uwp 標題欄
- win10 uwp 從Type 使用構造
- win10 uwp ImageSourece 和Byte[] 相互轉換
- win10 uwp 驗證TextBox
- C# 使用Emit深克隆