我遇到过几种将渐变样式应用于Windows窗体应用程序中的对象的方法。所有方法都涉及覆盖OnPaint方法。但是,我正在寻找基于验证在运行时更改样式。
如何将新的渐变样式应用于已渲染的按钮(就像我可以使用BackColor一样)?
R, 下进行。
更新:这是我目前使用的代码。它似乎没有效果
private void Button_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
Graphics g = e.Graphics;
g.DrawString("This is a diagonal line drawn on the control",
new Font("Arial", 10), System.Drawing.Brushes.Blue, new Point(30, 30));
g.DrawLine(System.Drawing.Pens.Red, btn.Left, btn.Top,
btn.Right, btn.Bottom);
this.btn.Invalidate();
}
被
召唤btn.Paint += new PaintEventHandler(this.Button_Paint);
使用当前代码进一步更新
private void Button_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
g.DrawString("This is a diagonal line drawn on the control",
new Font("Arial", 10), System.Drawing.Brushes.Blue, new Point(30, 30));
g.DrawLine(System.Drawing.Pens.Red, btn.Left, btn.Top,
btn.Right, btn.Bottom);
}
private void btn_Click(object sender, EventArgs e)
{
btn.Paint += new PaintEventHandler(this.Button_Paint);();
btn.Invalidate();
}
答案 0 :(得分:3)
这有两个部分。一,正如SLaks所说,你需要在Paint
事件处理程序中绘制渐变。这看起来像这样(为了简洁起见,我的例子有点乱):
private void Button_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
if (MyFormIsValid()) {
g.DrawString("This is a diagonal line drawn on the control",
new Font("Arial", 10), System.Drawing.Brushes.Blue, new Point(30, 30));
g.DrawLine(System.Drawing.Pens.Red, btn.Left, btn.Top,
btn.Right, btn.Bottom);
}
else {
g.FillRectangle(
new LinearGradientBrush(PointF.Empty, new PointF(0, btn.Height), Color.White, Color.Red),
new RectangleF(PointF.Empty, btn.Size));
}
}
此外,您需要进行验证并在单击时重绘按钮:
btn.Click += Button_Click;
...
private void Button_Click(object sender, EventArgs e)
{
DoValidations();
btn.Invalidate();
}
当然,您必须实施DoValidations()
和MyFormIsValid()
方法。
以下是一个可运行的示例程序:http://pastebin.com/cfXvtVwT
答案 1 :(得分:2)
如您所见,您需要处理Paint
事件。
您可以在类中设置一个布尔值来指示是否绘制渐变。