本文翻译:https://mobileprogrammerblog.wordpress.com/2015/12/23/live-tiles-and-notifications-in-universal-windows-10-app/ 我会写很多质量很低文章,文章都是胡说,如果看不懂可以发到邮箱

动态磁贴是看起来很好看的东西,放在开始菜单,看来是下面图

win10总有很多看起来有用,但实际没什么卵用的东西,我一点不觉得用户觉得这个有用,但是我们能做活动磁贴UWP,微软一直把开发者当成用户。

做一个UWP当然需要我们打开神器

新建一个项目,空UWP,可以使用快捷键ctrl+shift+N

我们打开MainPage.xaml,新建的时候有点慢,我们需要等一下如果放在固态基本不用等。

    <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

    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

    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

    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

{"Description":"A test task","Id":"9d6c3585-d0c2-4885-8fe0-f02727f8e483","IsComplete":true}

我们把刚才写的MainPage的按钮绑定到

    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/

win10 uwp 活动磁贴的更多相关文章

  1. 【Win10 UWP】后台任务与动态磁贴

    动态磁贴(Live Tile)是WP系统的大亮点之一,一直以来受到广大用户的喜爱.这一讲主要研究如何在UWP应用里通过后台任务添加和使用动态磁贴功能. 从WP7到Win8,再到Win10 UWP,磁贴 ...

  2. Win10 UWP版《芒果TV》v2.4.0直播超女,芒果台综艺一网打尽

    Win10 UWP版<芒果TV>直播超女,芒果台综艺一网打尽 Win10版UWP<芒果TV>自2015年9月登录商店以来,一直在持续更新,积极改进,拥有芒果台视频的独家点播和直 ...

  3. Win10 UWP开发系列:使用VS2015 Update2+ionic开发第一个Cordova App

    安装VS2015 Update2的过程是非常曲折的.还好经过不懈的努力,终于折腾成功了. 如果开发Cordova项目的话,推荐大家用一下ionic这个框架,效果还不错.对于Cordova.PhoneG ...

  4. Win10 UWP开发系列:实现Master/Detail布局

    在开发XX新闻的过程中,UI部分使用了Master/Detail(大纲/细节)布局样式.Win10系统中的邮件App就是这种样式,左侧一个列表,右侧是详情页面.关于这种 样式的说明可参看MSDN文档: ...

  5. Win10 UWP开发实现Bing翻译

    微软在WP上的发展从原来的Win7到Win8,Win8.1,到现在的Win10 UWP,什么是UWP,UWP即Windows 10 中的Universal Windows Platform简称.即Wi ...

  6. Win10/UWP开发—使用Cortana语音与App后台Service交互

    上篇文章中我们介绍了使用Cortana调用前台App,不熟悉的移步到:Win10/UWP开发—使用Cortana语音指令与App的前台交互,这篇我们讲讲如何使用Cortana调用App的后台任务,相比 ...

  7. 【Win10 UWP】URI Scheme(一):Windows Store协议的解析和使用

    协议是Windows Phone和Windows Store应用的一个重要特点,可以做到在不同应用之间进行互相呼起调用.小小协议,学问大着呢.我打算写几篇关于协议在UWP中使用的文章. 这一讲的主要对 ...

  8. 【Win10 UWP】QQ SDK(二):SDK的回调处理

    上一讲,我们介绍了QQ SDK的使用方法,请看<[Win10 UWP]QQ SDK(一):SDK基本使用方法> 一. 回调的基本形式 从前面的介绍中我们知道,我们的应用和QQ客户端之间需要 ...

  9. Win10 UWP应用发布流程

    简介 Win10 UWP应用作为和Win8.1 UAP应用不同的一种新应用形式,其上传至Windows应用商店的流程也有了一些改变. 这篇博文记录了我们发布一款Win10 UWP应用的基本流程,希望为 ...

随机推荐

  1. java--整理下关于static关键字的知识

    如果将域定义为static,每个类中只有一个这样的域.而每一个对象对于所有的实例域却都有自己的一份拷贝.--<java核心技术> 使用static的两种情形:1.只想为某特定域分配单一存储 ...

  2. 团队作业4——第一次项目冲刺(Alpha版本)1st day

    一.Daily Scrum Meeting照片 二.燃尽图 三.项目进展 1.界面 主界面以及游戏界面大体上完成了 界面内的功能正在写 2.登陆方面 QQ授权还未申请 申请完在登陆界面完成后实现用QQ ...

  3. 201521123111《Java程序设计》第14周学习总结

    本次作业参考文件 MySql操作视频与数据库相关jar文件请参考QQ群文件. 1. 本周学习总结 1.1 以你喜欢的方式(思维导图.Onenote或其他)归纳总结多数据库相关内容. 连接数据库前,应先 ...

  4. 201521123019 《Java程序设计》第11周学习总结

    1. 本章学习总结 2. 书面作业 Q1.互斥访问与同步访问 完成题集4-4(互斥访问)与4-5(同步访问) 1.1除了使用synchronized修饰方法实现互斥同步访问,还有什么办法实现互斥同步访 ...

  5. linux(CentOS5.8)环境下搭建Radius

    本文记录了freeRadius在CentOS5.8环境下的基本搭建过程,未涉及mysql的加入及配置 freeradius官方地址:http://freeradius.org/ 环境:CentOS5. ...

  6. ecshop商城系统登录出现登录闪退问题

    症状:ecshop商城系统提示登录成功,而且状态也是登录,一刷新,自动退出了,真坑爹 解决方案: 1.点着点着经常无故退出,感觉session被清空了.查找原因:ecshop中有用ip地址来验证,而公 ...

  7. Ring3层 UNICODE_STRING

    今天写驱动用到UNICODE_STRING,就在Ring3层抠了一些源代码,学习一下,不多说了上代码了 #pragma once #include <windows.h> #include ...

  8. Python接口测试自动化说明及代码实例:含get、post、put、delete等方法

    一.接口说明文档 环境准备: 安装火狐 安装插件: httprequester https://addons.mozilla.org/en-US/firefox/addon/httprequester ...

  9. 第一次安装jshint,jshint新手使用记录

    刚刚出来工作的渣渣,第一次进入这样比较正规的公司,各个开发流程都比较严格,代码也是要经过jshint的检测才能上传到svn才能成功打包项目.所以我这种技术都半桶水的职场开发小白,也是第一次用jshin ...

  10. 微信支付之h5方式(非微信内置浏览器中支付)

    这两天完成了公司网站手机和PC端的支付对接,就是支付宝和微信. 对接完后有所感触,我们来聊一聊,微信支付的坑,为什么这么说呢,因为我在对接完支付宝后是很愉快的,基本上在demo上稍加修改就ok了, 对 ...