2015-08-25 181 views
5

我正在开发C#(Visual Studio 2015)中的程序,我想在某种情况下向用户显示Toast消息。我从网上下载MSDN这个代码,它运行的罚款:显示Windows 10 Toast通知

// Get a toast XML template 
XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastImageAndText04); 

// Fill in the text elements 
XmlNodeList stringElements = toastXml.GetElementsByTagName("text"); 
for (int i = 0; i < stringElements.Length; i++) 
{ 
    stringElements[i].AppendChild(toastXml.CreateTextNode("Line " + i)); 
} 

// Specify the absolute path to an image 
String imagePath = "file:///" + Path.GetFullPath("toastImageAndText.png"); 
XmlNodeList imageElements = toastXml.GetElementsByTagName("image"); 
imageElements[0].Attributes.GetNamedItem("src").NodeValue = imagePath; 

// Create the toast and attach event listeners 
ToastNotification toast = new ToastNotification(toastXml); 
toast.Activated += ToastActivated; 
toast.Dismissed += ToastDismissed; 
toast.Failed += ToastFailed; 

// Show the toast. Be sure to specify the AppUserModelId on your application's shortcut! 
ToastNotificationManager.CreateToastNotifier(APP_ID).Show(toast); 

测试这个代码,我想落实到我的应用程序后。所以我改变了一点,试图运行它。错误消息:

类型“IReadOnlyList <>”在未引用的程序集中定义。添加一个参考System.Runtime,版本= 4.0.0.0,文化=中性公钥= b03f5f7f11d50a3a” (翻译)

也是一样IEnumerable<>IReadOnlyList<>

错误来自于这两条线:

for (int i = 0; i < stringElements.Length; i++) 
{ 
    stringElements[i].AppendChild(toastXml.CreateTextNode("Line " + i)); 

我也尝试添加引用System.Runtime。我的NuGet(https://www.nuget.org/packages/System.Runtime/4.0.0/)。 之后的错误都不见了下载了它,但现在literaly 我的代码中的单词是红色的,像“System.Object未定义”等错误(但它仍然在我启动时运行!)。

我能想到的唯一可能的解决方案是System.Runtime已经安装在我的电脑的某个地方,而4.0.0是我的程序的错误版本。但我无法在任何地方找到它。

PS:这是一个桌面应用程序,而不是Windows Store应用程序。

+0

在错误出现之前,您发生了什么变化?因为我理解你的问题,如果你不改变任何东西,MSDN的代码工作正常吗? –

回答

10

我认为这是相同的问题this question 您必须添加到

参考
C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5.1\Facades\System.Runtime.dll 

PS:如果你有一个Windows 10只有桌面应用程序,您可能需要使用新的土司制度, MSDN上的代码示例使用Windows 8。它适用于W10,但没有全部新功能(微软发布官方NuGet包)。

编辑:既然我无法评论,我将张贴在这里的答案:

唯一的例外是,因为你需要提供一个applicationIdCreateToastNotifier()

ToastNotificationManager.CreateToastNotifier("MyApplicationId").Show(toast); 

它是将名称在行动中心用来组织你的敬酒(所以一般来说,你把你的应用程序的名称)。在Windows 8.1中,需要注册您的应用程序ID(我认为这是来自MSDN的示例),但现在您可以放置​​应用程序的名称。

GetXml()只适用于WinRT。在桌面上,您需要像使用GetContent()一样进行操作。

+0

谢谢,异常消失了。但现在的问题是只有一个标准的吐司会显示 - 吐司不显示我的标题/正文。我正在使用 'Windows.Data.Xml.Dom。XmlDocument doc = new Windows.Data.Xml.Dom.XmlDocument(); doc.LoadXml(content.GetContent()); ToastNotificationManager.CreateToastNotifier(“Bether”)。Show(toast);' 变量'content'属于'ToastContent'类型 - 在这里我指定了我自己的文本等,但它没有显示 - 只有stanard“新通知“。 – Bobface

+2

@Bobface当吐司包含无效数据,尤其是图像时,通常会出现此问题。就我个人而言,我无法在驱动器上使用相对路径来映像,所以我不得不使用绝对路径。 – k94ll13nn3