How to create a clickable links in ListView?

2019-02-15 13:10发布

问题:

I am trying to make URL clickable inside of ListView item.

How do I do this?

The way I want it to work is to user store link in plain text, and then when I am retrieving the links I want to make them clickable in ListView.

This is how I retrieve entries from my database while read.GetString(2) pulls the URL value:

if (security.DecryptAES
    (read.GetString(1), storedAuth.Password, 
    storedAuth.UserName) == "Web Site Password")
{
    // Count Web passwords.
    countWeb++;
    Web = new ListViewItem("");
    Web.SubItems.Add(security.DecryptAES
        (read.GetString(2), storedAuth.Password, storedAuth.UserName));
    Web.SubItems.Add(security.DecryptAES
        (read.GetString(5), storedAuth.Password, storedAuth.UserName));
    Web.SubItems.Add(security.DecryptAES
        (read.GetString(6), storedAuth.Password, storedAuth.UserName));
    Web.Tag = read.GetInt32(0);
    lvWeb.Items.Add(Web);
}

回答1:

The first thing you want to do is give visual feedback to let the user know that the item is clickable. I'll just arbitrarily assume the url is in the 2nd column. Add the MouseMove event for the ListView:

    private void listView1_MouseMove(object sender, MouseEventArgs e) {
        var hit = listView1.HitTest(e.Location);
        if (hit.SubItem != null && hit.SubItem == hit.Item.SubItems[1]) listView1.Cursor = Cursors.Hand;
        else listView1.Cursor = Cursors.Default;
    }

The next step is very similar, implement the MouseUp event to detect a click on the sub-item:

    private void listView1_MouseUp(object sender, MouseEventArgs e) {
        var hit = listView1.HitTest(e.Location);
        if (hit.SubItem != null && hit.SubItem == hit.Item.SubItems[1]) {
            var url = new Uri(hit.SubItem.Text);
            // etc..
        }
    }