如何根据动态值填充面板背景颜色

How to fill panel background color based on dynamic value

我正在使用 C# 开发一个桌面应用程序,如果面板宽度为 200px 且进度 属性 当前达到 50%,则需要使用动态 values.For 示例填充面板背景那么面板的 100px 应该是绿色的,剩下的 100px 就是绿色。

这里有一个简单的控件可以完成这项工作

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);

    }
}

只需在您的项目中创建一个新的空 class 并将其命名为 ProgressPanel 然后将上面的代码复制到其中。

现在您可以像使用设计器中的任何其他控件一样使用新创建的 ProgressPanel

请注意,此示例是一个简化的示例。 你可能会注意到一些闪烁,但除此之外它完全正常

如果您想知道如何将此示例升级为专业控件,我很乐意提供帮助