簡體   English   中英

WPF:ComboBox中的多個前景色

[英]WPF: multiple foreground colors in a ComboBox

在XAML中,我們可以為ComboBox每個項設置特定屬性,例如:

<ComboBoxItem Foreground="Blue" Background="AntiqueWhite" Content="First Item"/>
<ComboBoxItem Foreground="Yellow" Background="Red" Content="Second Item"/>

當我從代碼動態填充ComboBox時嘗試執行此操作時, ComboBox .Foreground屬性會在所有項目上設置前景值。 我想知道是否有任何方法可以在代碼中實現這一點(為不同的項目設置不同的前景色)。

例如:

ComboBox1[First Item].Foreground = Brushes.Red;
ComboBox1[Second Item].Foreground = Brushes.Blue;

嘗試將ComboBox的Item轉換為ComboBoxItem類型,然后設置它的Foreground屬性而不是整個ComboBox的Foreground

((ComboBoxItem)ComboBox1.Items[0]).Foreground = Brushes.Red;

更新:

如果您通過以下方式從代碼向ComboBox1添加新項:

ComboBox1.Items.Add(new ComboBoxItem {Content = "Third Item"});

轉換將正常工作,因為上面的代碼類似於你所展示的XAML對應代碼。 但是如果你這樣做的話:

ComboBox1.Items.Add("Third Item");

鑄造不起作用。 因為該代碼將字符串添加到ComboBox Item而不是ComboBoxItem對象。 在這種情況下,獲取ComboBoxItem並不是那么簡單,您需要使用ItemContainerGenerator來獲取它,如下所示:

var comboBoxItem = (ComboBoxItem)ComboBox1.ItemContainerGenerator.ContainerFromItem(ComboBox1.Items[0]);
comboBoxItem.Foreground = Brushes.Red;

試試這個:

XAML

<Grid>
    <ComboBox Name="TestComboBox"
              Width="100"
              Height="30"
              Loaded="TestComboBox_Loaded">

        <ComboBoxItem Content="First Item"/>            
        <ComboBoxItem Content="Second Item"/>
    </ComboBox>
</Grid>

Code-behind

private void TestComboBox_Loaded(object sender, RoutedEventArgs e)
{
    var comboBox = sender as ComboBox;

    if (comboBox != null) 
    {
        var firstItem = comboBox.Items[0] as ComboBoxItem;
        var secondItem = comboBox.Items[1] as ComboBoxItem;

        if (firstItem != null && secondItem != null)  
        {
            firstItem.Foreground = Brushes.Red;
            secondItem.Foreground = Brushes.Blue;
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM