2016-04-08 31 views
0

Bir döngüde birden çok nesneyi değiştirmek nasıl mümkündür. Örneğin, 30 düğmeniz var ve arka plan rengini değiştirmek istiyorsunuz. Düğme1, düğme2 ve benzeri denir.Bir döngü içinde adlarına göre birden çok nesneyi işleme

for (int i=1; i<31; i++) 
{ 
    button+i.BACKGROUND.COLOR = AWESOME.BACKGROUND.COLOR; 
} 

Yani "button + i" için doğru sözdizimi nedir? veya bunu yapmanın daha verimli bir yolu var mı?

+3

ile çalışmak daha sonra 'Collection' koyun ve o Koleksiyon. –

+1

Neden bunun için bir dizi veya düğme listesi oluşturmuyorsunuz? –

+0

WPF? WinForms? WebForms? MVC? ...? –

cevap

0

Tüm düğmeleri bir listeye koyabilir ve foreach kullanabilir misiniz?

List<Button> buttons = new List<Button>(); 
//at some point, in a constructor or Loaded event add all the buttons that have been created to the list 
foreach(var button in buttons) 
{ 
} 

Yapabilirsin teorik yansıma yoluyla düğmeleri almak ve düğmeler var olacaktır bildiğinde bir noktada, bir listeye ekleyin:

var t = this.GetType(); 

var fields = t.GetFields(BindingFlags.NonPublic | 
        BindingFlags.Instance); 
//assuming you are doing this in a xaml.cs, if not you may need to change 
// the above to GetProperties or use Public flag, depending on how your buttons 
// are defined. 
foreach (var f in fields) 
{ 
    if (f.FieldType == typeof (Button)) 
     _buttons.Add(f.GetValue(this)); 

} 
İlgili konular