简体   繁体   English

C#更改在运行时添加到Winform的控件的属性

[英]C# Change properties of control added at runtime to winform

I need to add a variable number of progress bars to a form and then update them as required. 我需要将可变数量的进度条添加到表单,然后根据需要更新它们。 I can add the progress bars fine, but cannot find a way to update their properties. 我可以添加进度条,但是找不到更新其属性的方法。

int pbCount = 0;
void AddProgressBar(int, pbX, int pbY, int initalValue) 
{
    pbCount++;
    ProgressBar MyBar = new ProgressBar();
    MyBar.Name = "MyBar" + pbCount.ToString();
    MyBar.Location = new System.Drawing.Point(pbX, pbY);
    MyBar.Width = 200;
    MyBar.Height = 20;
    MyBar.Minimum = 0;
    MyBar.Maximum = 100;
    MyBar.Value = initialValue;
    this.Controls.Add(MyBar);
}

So how do I change the value of a given Progress Bar? 那么,如何更改给定进度条的值?

Or is there a better way of adding the Progress Bars for updating later? 还是有一种更好的方式添加进度条以便以后进行更新?

Try this: 尝试这个:

ProgressBar bar7 = this.Controls.OfType<ProgressBar>().FirstOrDefault( x => x.Name == "MyBar7" );

If it doesn't find "MyBar7" it will return null. 如果找不到“ MyBar7”,它将返回null。

Then you can update properties as needed. 然后,您可以根据需要更新属性。

Another option would be to also store the progress bars in a Dictionary< string, ProgressBar >; 另一种选择是将进度条也存储在Dictionary< string, ProgressBar >;

Here is an example using LinqPad: 这是使用LinqPad的示例:

It shows how to add a new ProgressBar to the dictionary, and how to get it from the dictionary. 它显示了如何向字典添加新的ProgressBar,以及如何从字典中获取它。

You could probably also just use a simple array if you want to access the ProgressBars by index. 如果要按索引访问ProgressBar,则可能还可以只使用一个简单的数组。

Dictionary<string,ProgressBar> ProgressBars = new Dictionary<string,ProgressBar>();

void Main()
{
    ProgressBars["MyBar1"] = new ProgressBar();

    //... later on
    ProgressBar progressBar = ProgressBars["MyBar1"];
    progressBar.PerformStep();
    progressBar.Step = 77;

    progressBar.Step.Dump();

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM