我有多个图片框,我需要在运行时加载随机图像.因此我认为拥有所有图片框的集合然后使用简单的循环将图像分配给它们会很好.但是我应该怎么做呢?或许还有其他更好的解决方案可以解决这个问题吗?
Fem*_*ref 78
使用一点LINQ:
foreach(var pb in this.Controls.OfType<PictureBox>())
{
//do stuff
}
Run Code Online (Sandbox Code Playgroud)
但是,这只会处理主容器中的PictureBoxes.
cdh*_*wie 26
你可以使用这个方法:
public static IEnumerable<T> GetControlsOfType<T>(Control root)
where T : Control
{
var t = root as T;
if (t != null)
yield return t;
var container = root as ContainerControl;
if (container != null)
foreach (Control c in container.Controls)
foreach (var i in GetControlsOfType<T>(c))
yield return i;
}
Run Code Online (Sandbox Code Playgroud)
然后你可以做这样的事情:
foreach (var pictureBox in GetControlsOfType<PictureBox>(theForm)) {
// ...
}
Run Code Online (Sandbox Code Playgroud)
如果你至少在.NET 3.5上,那么你就拥有了LINQ,这意味着自从ControlCollection实现IEnumerable你可以做到:
var pictureBoxes = Controls.OfType<PictureBox>();
Run Code Online (Sandbox Code Playgroud)
我使用这个通用的递归方法:
此方法的假设是,如果控件是 T,则该方法不会查看其子级。如果您还需要查看其子项,您可以轻松地相应地更改它。
public static IList<T> GetAllControlsRecusrvive<T>(Control control) where T :Control
{
var rtn = new List<T>();
foreach (Control item in control.Controls)
{
var ctr = item as T;
if (ctr!=null)
{
rtn.Add(ctr);
}
else
{
rtn.AddRange(GetAllControlsRecusrvive<T>(item));
}
}
return rtn;
}
Run Code Online (Sandbox Code Playgroud)
小智 5
一个简单的函数,易于理解,递归,并且可以在任何表单控件内调用它:
private void findControlsOfType(Type type, Control.ControlCollection formControls, ref List<Control> controls)
{
foreach (Control control in formControls)
{
if (control.GetType() == type)
controls.Add(control);
if (control.Controls.Count > 0)
findControlsOfType(type, control.Controls, ref controls);
}
}
Run Code Online (Sandbox Code Playgroud)
您可以通过多种方式调用它。获取按钮:
List<Control> buttons = new List<Control>();
findControlsOfType(typeof(Button), this.Controls, ref buttons);
Run Code Online (Sandbox Code Playgroud)
获取面板:
List<Control> panels = new List<Control>();
findControlsOfType(typeof(Panel), this.Controls, ref panels);
Run Code Online (Sandbox Code Playgroud)
ETC。
| 归档时间: |
|
| 查看次数: |
68775 次 |
| 最近记录: |