问题
how is the foreground text color changed (not the selected text, or the background of the selection) in a wpf listbox? say, for example, i wanted to make all the letter "a" items green, all the letter "b" items red, etc? how can i programmatically do that as i add them in c#? all i can find is people posting about changing selected text, i want to change the color of the foreground text to make it look more organized .
on a side note, why is stackoverflow giving me problems about this question? says the question "doesn't meet quality standards". i think this is a perfectly legitimate question. what filter is put on this question that makes it not meet any standards?
i'm looking to do this:
string[] pics= Directory.GetFiles(@"C:\\", "*.jpg");
foreach (string pic in pics)
{
CHANGE THE FOREGROUND COLOR TO RED
lbxFileList.Items.Add(pic);
}
string[] vids= Directory.GetFiles(@"C:\\", "*.mpg");
foreach (string vid in vids)
{
CHANGE THE FOREGROUND COLOR TO GREEN
lbxFileList.Items.Add(vid);
}
回答1:
Use a template in combination with a converter:
<ListBox x:Name="lbxFileList">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Path=.}" ForeGround={Binding ., Converter={StaticResource ItemToBrushConverter}}/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
The converter should convert your Item to a Brush
that has the color you want:
class FileNameToColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter,
CultureInfo culture)
{
return value.EndsWith("mpg") ? Brushes.Green : Brushes.Red;
}
public object ConvertBack(object value, Type targetType, object parameter,
CultureInfo culture)
{
throw new NotImplementedException();
}
}
回答2:
I agree with the previous answer, but you could also add listboxitems to your listbox (instead of strings), that way you could change the foreground color before adding it to the listbox.
回答3:
To build on the above solution:
foreach (string pic in pics)
{
if (string.IsNullOrEmpty(pic))
continue;
string first = pic.Substring(0, 1);
Color color;
switch (first.ToLower())
{
case "a":
color = Colors.Green;
break;
case "b":
color = Colors.Red;
break;
default:
color = Colors.Black;
}
ListBoxItem item = new ListBoxItem() {
Content = pic,
Foreground = new SolidColorBrush(color)
};
lbxFileList.Items.Add(pic);
}
来源:https://stackoverflow.com/questions/6161744/how-is-the-foreground-color-changed-on-just-one-line-of-wpf-listbox