2012-06-30 57 views
7
<Grid x:Name="LayoutRoot"> 
    <ComboBox x:Name="com_ColorItems" Height="41" Margin="198,114,264,0" VerticalAlignment="Top" FontSize="13.333" FontWeight="Bold" Foreground="#FF3F7E24"/> 
</Grid> 

通過上面的代碼,我爲組合框綠色中的所有項目着色。如何在wpf中動態更改組合框特定項目顏色

private void Window_Loaded(object sender, RoutedEventArgs e) 
{ 
     for (int i = 0; i < 5; i++) 
     { 
      com_ColorItems.Items.Add(i); 
     } 
} 

通過上面的代碼,我將五個項目填充到組合框中。現在我想動態地將第三項(3)的顏色更改爲代碼後面的「紅色」。我怎樣才能做到這一點?

回答

10

而是在組合框中加入i實際值,添加ComboBoxItem代替:

private void Window_Loaded(object sender, RoutedEventArgs e) 
    { 
     for (int i = 0; i < 5; i++) 
     { 
      ComboBoxItem item = new ComboBoxItem(); 

      if (i == 2) item.Foreground = Brushes.Blue; 
      else item.Foreground = Brushes.Pink; 

      item.Content = i.ToString(); 
      com_ColorItems.Items.Add(item); 
     } 
    } 

如果要修改這個方法後創建的ComboBoxItem,這是你如何能做到這一點:

var item = com_ColorItems.Items[2] as ComboBoxItem; // Convert from Object 
if (item != null)         // Conversion succeeded 
{ 
    item.Foreground = Brushes.Tomato; 
} 
1

首先,嘗試綁定你的Source並避免通過後面的代碼直接訪問。 而且你可以在你的ItemSource綁定中使用Converter。

例如

ItemSource={Binding MyComboboxItems, Converter={StaticResource MyConverter}} 

,並在你的轉換器找到你的第3項,並給他們一個不同的ForegroundColor

+0

你能給一個小例子。什麼是MyComboboxItems的類型? – marbel82

相關問題