How to fill panel background color based on dynamic value [closed]

走远了吗. 提交于 2021-01-29 17:45:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!