问题
I am working on an desktop application in C# that requires a panel background to be filled using dynamic values.For example if the panel of width 200px and the progress property is currently reached at 50% then 100px of the panel should have green color in it rest 100px will be as it.
回答1:
here's a simple control that does the job
public partial class ProgressPanel : Panel
{
private float m_progress = 0;
private Color m_progressColor = Color.Green;
public ProgressPanel()
{
InitializeComponent();
}
/// <summary>
/// the progress value is between 0 & 100 inclusively
/// </summary>
public float Progress
{
get
{
return m_progress;
}
set
{
m_progress = value;
this.Invalidate();
}
}
public Color ProgressColor
{
get
{
return m_progressColor;
}
set
{
m_progressColor = value;
this.Invalidate();
}
}
private void ProgressPanel_Paint(object sender, PaintEventArgs e)
{
e.Graphics.Clear(BackColor);
e.Graphics.FillRectangle(new SolidBrush(ProgressColor), new Rectangle(new Point(), new Size((int)(Width * Progress / 100), Height)));
}
private void InitializeComponent()
{
this.SuspendLayout();
//
// ProgressPanel
//
this.Paint += new System.Windows.Forms.PaintEventHandler(this.ProgressPanel_Paint);
this.ResumeLayout(false);
}
}
just create a new empty class in your project & name it ProgressPanel
then copy the above code into it.
now you can use your newly created ProgressPanel
as you would use any other control from the designer
note that this example is a simplified one. you may notice some flickering, but other than this it's totally functional
if you want to know how to upgrade this example to a professional control, I'd be happy to help
来源:https://stackoverflow.com/questions/58103658/how-to-fill-panel-background-color-based-on-dynamic-value