2012-02-29 18 views
2

所以我想將當前選定的按鈕設置爲列表框中的綠色背景,而未選擇的所有按鈕都應該保持黑色。我怎樣才能做到這一點。查看下面的示例代碼..不能讓它工作。在列表框中一次選擇了一個按鈕(背景顏色)

foreach(Button btn in ListBox.Items) 
btn.Background = new SolidColorBrush(Colors.Black); 
Button clickedButton = sender as Button; 
clickedButton.Background = new SolidColorBrush(Colors.Green); 
+0

安置自己的ItemTemplate或w/e你正在填充按鈕。你需要ListBox中的按鈕嗎?您可以使用VisualState執行此行爲。 – 2012-02-29 20:48:42

回答

2

如果你想用那種方式(不綁定和轉換器),在這裏你去: (我還假設,只有一個按鈕,在列表框中項)

for (int i = 0; i < ListBox.Items.Count; i++) 
{ 
    Button currentButton = ListBox.Items[i] as Button; 
    if(currentButton != null) 
    { 
     if (i == ListBox.SelectedIndex) 
      currentButton.Background = new SolidColorBrush(Colors.Green); 

     else 
      currentButton.Background = new SolidColorBrush(Colors.Black); 
    } 
} 
相關問題