0

我有一个返回标签集合的方法,尽管我可以设置标签的属性,但我想定义标签的绘制事件,以便我可以以某种格式在那里绘制项目。

 public List<Label> drawLabel()
        {
            lstLable = new List<Label>();
            foreach (cOrderItem item in currOrder.OrderItems)
            {
                _lbl = new Label();
                _lbl.Width = 200;// (int)CanvasWidth;
                _lbl.BackColor = Color.AliceBlue;
                _lbl.Text = item.ProductInfo.ProductDesc;
                _lbl.Height = 20;
                _lbl.Dock = DockStyle.Top;
                _lbl.Paint()////this is the event i want to define for drawign purpose.
                lstLable.Add(_lbl);

            }
            return lstLable;
        }

我将此集合返回到一个表单,我将在其中获取每个标签并添加到面板中。

4

4 回答 4

1

不清楚您是指 winforms、wpf 还是 webforms,但在 winforms 中只需使用Control.Paint -event 作为任何其他事件:

public List<Label> drawLabel()
{
    lstLable = new List<Label>();
    foreach (cOrderItem item in currOrder.OrderItems)
    {
        _lbl = new Label();
        _lbl.Width = 200;// (int)CanvasWidth;
        _lbl.BackColor = Color.AliceBlue;
        _lbl.Text = item.ProductInfo.ProductDesc;
        _lbl.Height = 20;
        _lbl.Dock = DockStyle.Top;

        //this is the event i want to define for drawign purpose.
        _lbl.Paint += new PaintEventHandler(LblOnPaint);

        lstLable.Add(_lbl);

    }
    return lstLable;
}

// The Paint event method
private void LblOnPaint(object sender, PaintEventArgs e)
{
    // Example code:

    var label = (Label)sender;

    // Create a local version of the graphics object for the label.
    Graphics g = e.Graphics;

    // Draw a string on the label.
    g.DrawString(label.Text, new Font("Arial", 10), Brushes.Blue, new Point(1, 1));
}
于 2013-09-09T13:45:33.607 回答
1

使用 ObservableCollection 而不是 List

您还可以学习使用Reactive Extensions

于 2013-09-09T13:34:35.830 回答
1

可以订阅Label类的paint事件

_lbl.Paint+=yourCustomPaintMethod;
于 2013-09-09T13:34:35.817 回答
1

我会将标签控件子类化并覆盖方法OnPaint

于 2013-09-09T13:38:30.027 回答