我又遇到了问题。我的问题是我不知道如何在XML文件中存储超链接以及如何从那里将其检索到WPF ListBox 。在我的应用程序中,我按以下方式编写XML文件:
<?xml version="1.0" encoding="utf-8" ?>
<Books xmlns="">
<Category name="Computer Programming">
<Book>
<Author>H. Schildt</Author>
<Title>C# 4.0 The Complete Reference</Title>
<!--This is a hyperlink description-->
<Link>https://www.mcgraw-hill.co.uk/html/007174116X.html</Link>
</Book>
</Category>
</Books>
在Window Resources部分的XAML中,我按以下方式编写:
<Window.Resources>
. . . . . . . . . .
<DataTemplate x:Key="detailDataTemplate">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding XPath=Title}"/>
<TextBlock Text="{Binding XPath=Author}"/>
<TextBlock Text="{Binding XPath=Link}"/>
</StackPanel>
</DataTemplate>
. . . . . . . . . . .
</Window.Resources>
最后在ListBox标记中我写道:
<ListBox Name="lbxBooks" Grid.Row="1" Grid.Column="0"
. . . . . . . . . .
ItemTemplate="{StaticResource detailDataTemplate}"
IsSynchronizedWithCurrentItem="True"/>
但是在应用程序启动后,超链接在屏幕上显示为未启用的简单字符串,不允许鼠标单击以获取Internet资源。因此,作为对互联网资源的参考,它并没有正常工作。它显示为简单的文本字符串。 如何更正此错误并强制链接正常工作?我需要在XML文件和XAML中更正哪些内容?我非常感谢你的帮助。
答案 0 :(得分:0)
@ Hyperlink是一个字符串
WPF exmaple中的@ Hyperlink看here
@ generic XML工具:
public class SerializationHelper
{
public static void SerializeToXML<T>(T t, String inFilename) where T : class
{
StreamWriter textWriter = null;
try
{
var serializer = new XmlSerializer(t.GetType());
textWriter = new StreamWriter(inFilename);
serializer.Serialize(textWriter, t);
}
finally
{
if (textWriter != null) textWriter.Close();
}
}
public static T DeserializeFromXML<T>(String inFilename) where T : class
{
TextReader textReader = null;
T retVal = default(T);
try
{
var deserializer = new XmlSerializer(typeof(T));
textReader = new StreamReader(inFilename);
retVal = (T)deserializer.Deserialize(textReader);
return retVal;
}
finally
{
if (textReader != null) textReader.Close();
}
}
}
public class Book
{
public string Author { get; set; }
public string Title { get; set; }
public string Link { get; set; }
public string Catgegory { get; set; }
}
public class Data
{
public List<Book> Books { get; set; }
public Data()
{
Books = new List<Book>();
}
}
// ....
var filePath = "fileName.xml";
var bookList = new List<Book>();
bookList.Add(new Book
{
Author = "H. Schildt",
Link = @"https://www.mcgraw-hill.co.uk/html/007174116X.html",
Catgegory= "Computer Programming",
Title = "C# 4.0 The Complete Reference",
});
// save
SerializeToXML(new Data { Books = bookList }, filePath);
// load
var data = DeserializeFromXML<Data>(filePath);