且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

有没有办法在Windows窗体的LinkLabel控件中放置多个链接

更新时间:2023-12-06 16:37:16

是的,虽然我没有办法直接从设计者那里说出来,但是通过代码很容易管理:

Yes, though there isn't a way that I can tell to do it directly from the designer, but it is easy to manage via code:

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 事件包含对被点击的特定链接的引用,以便您可以访问与该链接关联的链接数据等.

Basically, the Links collection on the label can host a bunch of links in the LinkLabel. The LinkClicked event contains a reference to the specific link that was clicked so you can access the link data you associated with the link, among other things.

设计器只公开一个 LinkArea 属性,该属性默认包含 LinkLabel 的所有文本.添加到 Links 集合的第一个 Link 将自动更改 LinkArea 属性以反映集合中的第一个链接.

The designer only exposes a LinkArea property which defaults to include all of the text of the LinkLabel. The first Link you add to the Links collection will automatically change the LinkArea property to reflect the first link in the collection.

更接近您要求的内容如下所示:

Something a little closer to what you're asking would look like this:

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 事件发生时将其提取为字符串被解雇了.

I'm attaching the URL itself as the LinkData to the link's I'm creating in the loop so I can extract it out as a string when the LinkClicked event is fired.