你能帮我解决这段代码吗? 我想学习使用Invalidate和Update,但我不知道如何使用它 此代码不起作用。我想设置新文本,但它不“刷新”并且不写新字符串“Prova”。感谢
namespace Invalidate
{
public partial class Form1 : Form
{
private String txt;
private PointF xy;
public Form1()
{
InitializeComponent();
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawString("This is the text that prints!",
this.Font, System.Drawing.Brushes.Azure, 0, 0);
}
private void Form1_Load(object sender, EventArgs e)
{
Panel pHText = new Panel();
pHText.Name = "ctrId";
pHText.Location = new Point(10, 10);
pHText.Size = new Size(200, 200);
pHText.BackColor = Color.White;
pHText.Paint += paintingUrCtr;
Controls.Add(pHText);
}
private void paintingUrCtr(object sender, PaintEventArgs e)
{
Font myFont = new Font("Arial", 14);
e.Graphics.DrawLine(new Pen(Color.Black), 0, 0, 10, 10);
e.Graphics.DrawString(this.txt, myFont, Brushes.Blue, 10, 10);
}
public void setText(String text, PointF pos)
{
this.txt = text;
this.xy = pos;
}
private void button_Click(object sender, EventArgs e)
{
setText("Prova", new PointF(100, 100));
this.Invalidate();
this.Update();
}
}
}
答案 0 :(得分:0)
调用this.Invalidate();
不会使子控件无效,您需要使用重载that takes in a bool并传入true
private void button_Click(object sender, EventArgs e)
{
setText("Prova", new PointF(100, 100));
this.Invalidate(true);
this.Update();
}
编辑:正如评论中所提到的,您也可以使单个子控件无效并更新它。
private void button_Click(object sender, EventArgs e)
{
setText("Prova", new PointF(100, 100));
this.Controls["ctrId"].Invalidate(true);
this.Controls["ctrId"].Update();
}