C# 从Panel_Paint中的另一个类调用方法不会绘制任何内容
所以这应该很简单,但我看了一些类似的问题,找不到答案 我有一个C# 从Panel_Paint中的另一个类调用方法不会绘制任何内容,c#,graphics,C#,Graphics,所以这应该很简单,但我看了一些类似的问题,找不到答案 我有一个Form1类和一个电阻器类。在Form1类中,我有一个面板(我将名称更改为Canvas),在Canvas\u Paint方法中,我从电阻器类调用方法Draw,但没有绘制任何内容 表格1类别: public partial class Form1 : Form { static float lineWidth = 2.0F; static float backgroundLineWidth = 2.0F; sta
Form1
类和一个电阻器
类。在Form1
类中,我有一个面板
(我将名称更改为Canvas
),在Canvas\u Paint
方法中,我从电阻器
类调用方法Draw
,但没有绘制任何内容
表格1类别:
public partial class Form1 : Form
{
static float lineWidth = 2.0F;
static float backgroundLineWidth = 2.0F;
static Pen pen = new Pen(Color.Yellow, lineWidth);
static Pen backgroundPen = new Pen(Color.LightGray, backgroundLineWidth);
private bool drawBackground = true;
private List<Resistor> resistors = new List<Resistor>();
public Form1()
{
InitializeComponent();
}
private void Canvas_Paint(object sender, PaintEventArgs e)
{
if (drawBackground)
{
Console.WriteLine("Drawing background...");
Draw_Background(e.Graphics, backgroundPen);
}
if (resistors != null)
{
foreach (Resistor r in resistors)
{
//This does not work.
r.Draw(e.Graphics);
}
}
//The line below draws the line fine.
e.Graphics.DrawLine(pen, 0, 0, 100, 100);
}
private void Draw_Background(Graphics g, Pen pen)
{
for (int i = 0; i < Canvas.Width; i += 10)
{
g.DrawLine(pen, new Point(i, 0), new Point(i, Canvas.Height));
}
for (int j = 0; j < Canvas.Height; j += 10)
{
g.DrawLine(pen, new Point(0, j), new Point(Canvas.Width, j));
}
drawBackground = false;
}
private void AddResistor_Click(object sender, EventArgs e)
{
resistors.Add(new Resistor());
Console.WriteLine("Added a Resistor...");
}
}
我已经研究过这一点,它建议在这种情况下将e.Graphics
对象传递给Resistor
类中的Draw
方法,但该方法不起作用
我是C#的新手,因此我非常感谢您的帮助
编辑:
如果你想下载并试用的话,我会启动这个项目
编辑:
所以问题是,单击按钮后,没有调用panel Paint方法。解决方案是在
AddResistor\u单击方法中添加Canvas.Invalidate
,在调试器中运行代码,并在事件处理程序中放置断点,您将能够检查代码是否确实试图绘制某些内容。如果没有,那么是否调用过事件处理程序?你们的电阻器清单上有什么吗?如果它正在绘制,但您什么也看不到,那么您没有使用正确的图形上下文,或者您没有在控件的可见部分绘制对象,或者您正在使用后续的绘图代码绘制内容。问题是,当单击按钮时,面板的绘制方法没有被调用,因为我发现绘制方法总是被调用。解决方案是在AddResistor\u Click
方法中添加Canvas.Invalidate
private void AddResistor_Click(object sender, EventArgs e)
{
resistors.Add(new Resistor());
Console.WriteLine("Added a Resistor...");
Canvas.Invalidate();
}
您应该始终在Paint
事件处理程序中使用e.Graphics
。不惜一切代价避免CreateGraphics
;它不会像你期望的那样工作。他还忘了订阅绘画活动。@CodyGray谢谢你,我把它改成e.Graphics
@HansPassant你说的“订阅绘画活动”是什么意思?谢谢。请在设计器中选择面板。单击“属性”窗口中的闪电图标。双击绘制。+1:感谢您的回答,它实际上让我思考,我注意到当我单击按钮添加电阻器时,面板的绘制方法没有被调用,因此为了修复此问题,我在添加电阻器的方法中添加了画布。Invalidate
。
private void AddResistor_Click(object sender, EventArgs e)
{
resistors.Add(new Resistor());
Console.WriteLine("Added a Resistor...");
Canvas.Invalidate();
}