2011-10-24 37 views
0

我想更改WP7中许多按钮的属性Background如何使用Foreach更改WP7中多个按钮的属性?

我可以写这样的事:

Foreach (var item in (this.Content as Panel).Children) 
{ 
    If (Element is Button) 
    { 
     Element.Background = Color.red; 
    } 
} 

但这doesen't工作, Element.Background doesen't存在...

任何人都知道如何解决它???

+0

也许尝试编写有效的C#代码对于初学者? C#中的基本教程*是一个很好的开始。 –

回答

0

你可以尝试用

Element.BackColor = Color.Red 

,而不是

Element.Background = Color.Red 
2

尝试而不是通过控制循环的这个

//to be on the safe side first check 
    if(this.Content == null || !(this.Content is Panel) 
     return; 

    foreach (var item in (this.Content as Panel).Children) 
    { 
     if (item is Button) 
     { 
      Button b = item as Button; 
      b.Background = new SolidColorBrush(Colors.Red); 
     } 
    } 
+0

这并没有工作..计划说“的NullReferenceException是未处理的” AT“(This.Content为面板)。儿童) –

+0

所以,如果'this.Content = null'这意味着有它里面没有按钮 –

0

,尝试结合自己的背景色性的东西,是它是一个实现INotifyPropertyChanged的类,该属性返回一个SolidColorBrush,另一个控件的BackColor属性,或者任何你选择绑定的属性。这可以在Silverlight中完成,而不必循环控制。让系统管理控制外观,而不是自己写。

相关问题