有没有办法在 Windows 窗体的 LinkLabel
控件中放置多个链接?
如果我就这样设置
this.linkLabel.Text = "";
foreach (string url in urls)
{
this.linkLabel.Text += url + Environment.NewLine;
}
它将其合并为一个链接。
提前致谢。
最佳答案
是的,虽然我无法直接从设计者那里知道如何做,但是通过代码很容易管理:
var linkLabel = new LinkLabel();
linkLabel.Text = "(Link 1) and (Link 2)";
linkLabel.Links.Add(1, 6, "Link data 1");
linkLabel.Links.Add(14, 6, "Link data 2");
linkLabel.LinkClicked += (s, e) => Console.WriteLine(e.Link.LinkData);
基本上,Links标签上的集合可以在 LinkLabel
中承载一堆链接。 LinkClicked
事件包含对被单击的特定链接的引用,因此您可以访问与该链接关联的链接数据等。
设计器仅公开一个 LinkArea
属性,该属性默认包含 LinkLabel
的所有文本。您添加到 Links
集合的第一个 Link
将自动更改 LinkArea
属性以反射(reflect)集合中的第一个链接。
更接近您的要求的内容如下所示:
var addresses = new List<string> {
"http://www.example.com/page1",
"http://www.example.com/page2",
"http://www.example.com/page3",
};
var stringBuilder = new StringBuilder();
var links = new List<LinkLabel.Link>();
foreach (var address in addresses)
{
if (stringBuilder.Length > 0) stringBuilder.AppendLine();
// We cannot add the new LinkLabel.Link to the LinkLabel yet because
// there is no text in the label yet, so the label will complain about
// the link location being out of range. So we'll temporarily store
// the links in a collection and add them later.
links.Add(new LinkLabel.Link(stringBuilder.Length, address.Length, address));
stringBuilder.Append(address);
}
var linkLabel = new LinkLabel();
// We must set the text before we add the links.
linkLabel.Text = stringBuilder.ToString();
foreach (var link in links)
{
linkLabel.Links.Add(link);
}
linkLabel.AutoSize = true;
linkLabel.LinkClicked += (s, e) => {
System.Diagnostics.Process.Start((string)e.Link.LinkData);
};
我将 URL 本身作为 LinkData
附加到我在循环中创建的链接,以便在 LinkClicked
事件时将其作为字符串提取出来被解雇了。
关于c# - 有没有办法在 Windows 窗体的 LinkLabel 控件中放置多个链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29174546/