1

我希望我的一些链接标签有背景色填充,有点像这样:

Click here

但问题是你不能真正有一个可以点击的填充链接标签,你必须只点击文本(如果你在填充区域内点击,点击不会注册。)

所以另一种选择是有一个内部带有链接标签的面板,然后为链接标签和面板控件注册 Click 事件,以获得可点击的按钮效果

我们如何:

  • 在面板内创建一个链接标签,让它们中的任何一个响应点击事件_而无需注册两个控件的点击事件;或者:
  • 有一个一直有 10px 填充的 LinkLabel 并使链接标签完全可点击?
4

2 回答 2

3

其实一个LinkLabel可以包含很多个Links,根据你的要求(可以点击背景),我们只好用LinkLabelfor only 1个链接,因为所有的链接都有相同的背景区域,点击背景区域不能告诉我们是哪个链接被点击。为了处理点击每个链接,我们处理事件LinkClicked,但是为了通过允许用户点击整个背景区域来改变它的行为,我们必须Click像往常一样处理事件。如果需要,添加一些MouseEnterMouseLeave处理程序以更改背景色。这是代码:

//Setup the link data for the LinkLabel
linkLabel1.Links.Add(new LinkLabel.Link() {Description = "StackOverflow", LinkData = "http://www.stackoverflow.com"});
linkLabel1.Text = "Stackoverflow";
linkLabel1.BackColor = Color.LightGray;
//Add 10px padding around the link text 
linkLabel1.Padding = new Padding(10);
//Do this to change the Cursor to Hand pointer when mouse over the whole link
linkLabel1.Cursor = Cursors.Hand;
//Click event handler for your linkLabel1
private void linkLabel1_Click(object sender, EventArgs e) {
  //Try showing the URL which the link refers
  //we can use this info to, for example, visit the link
  MessageBox.Show(linkLabel1.Links[0].LinkData.ToString());
}
//MouseEnter event handler to change the BackColor accordingly
private void linkLabel1_MouseEnter(object sender, EventArgs e) {
  linkLabel1.BackColor = Color.Yellow;
}
//MouseLeave event handler to change the BackColor accordingly
private void linkLabel1_MouseLeave(object sender, EventArgs e){
  linkLabel1.BackColor = Color.LightGray;
}

注意:通过这种方式自定义,aLabel可以替换LinkLabel,我们只需要一些合适Font的 , TextAlign, Tag(for LinkData) ...

于 2013-08-31T15:19:47.030 回答
1

您可以通过使用 linklabel 的“Click”事件而不是使用“LinkClicked 事件”来使填充的链接标签可点击。

private void linkLabel1_Click(object sender, EventArgs e)
        {

             //Your code here
            MessageBox.Show("Clicked Me");
        }
于 2013-08-31T15:23:55.887 回答