c# - XmlNode AppendChild 适用于 C# 但不适用于 VB.Net
问题描述
我一直在 vb.net 中遇到以下错误消息,但在用 C# 完成的同一个项目中,这非常有效。手动将项目从 C# 转换为 VB 后,出现错误。任何建议,将不胜感激。
VB.Net:
Const App_ID As String = "WindowsToastTest"
Private Sub Button_Click(sender As Object, e As RoutedEventArgs)
' Get a toast XML template
Dim toastXml As XmlDocument = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastImageAndText03)
' Fill in the text elements
Dim stringElements As XmlNodeList = toastXml.GetElementsByTagName("text")
For i As Integer = 0 To stringElements.Length
stringElements(i).AppendChild(toastXml.CreateTextNode("Line " + i))
Next
' Specify the absolute path to an image
Dim imagePath As String = "file:///" + Path.GetFullPath("toastImageAndText.png")
Dim imageElements As XmlNodeList = toastXml.GetElementsByTagName("image")
imageElements(0).Attributes.GetNamedItem("src").NodeValue = imagePath
' Create the toast And attach event listeners
Dim toast As ToastNotification = New ToastNotification(toastXml)
' Show the toast. Be sure to specify the AppUserModelId on your application's shortcut!
ToastNotificationManager.CreateToastNotifier(APP_ID).Show(toast)
End Sub
C#:
namespace ToastSample
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private const String APP_ID = "ToastSample";
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
// Get a toast XML template
XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastImageAndText03);
// 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);
// Show the toast. Be sure to specify the AppUserModelId on your application's shortcut!
ToastNotificationManager.CreateToastNotifier(APP_ID).Show(toast);
}
}
}
解决方案
问题不在于 XML,而在于您的字符串连接。
在 VB.Net 中通过 & 和 + 连接字符串
当您string + number
在 vb 中使用时,它会尝试将字符串转换为数字,这就是为什么您会收到错误消息“从字符串“Line”转换为类型“Double”无效”。而是使用 &:
stringElements(i).AppendChild(toastXml.CreateTextNode("Line " & i))
希望有帮助。
推荐阅读
- python - 如何将带有 unicode 数据的行转换为 Py2 和 Py3 上的 latin-1 编码的 csv 数据?
- laravel - 在 Laravel 中使用多个控制器和模型的最佳方法是什么
- csv - 我正在尝试根据 csvfile 中的数据在屏幕上移动一个立方体,但它不起作用。有人可以帮我处理这段代码吗?
- javascript - 如何一键获取不同的值?
- vba - 如何使用 Connect_Net 的密码连接到 zk ua300?
- audio - WM8904 和 SAMV71 重复电路问题
- aws-lambda - 无服务器功能可以部署在 AWS 上,在本地调用,但在 AWS 上找不到
- jquery - 如何增加触摸屏复选框的可点击区域
- python - 如何使用自定义文本创建具有多种选择的模型?
- python - NumPy 数组元素在被选中时会发生奇怪的变化