WPF Binding: Set the text color of a list item.

I'm sure this is probably something basic in WPF, but I'm new to XAML syntax, I'm trying to wrap my head around it.

Customization

I have a LogItem type - only POCO:

 public class LogItem { public string Message {get;set;} public Color MessageColor {get;set;} } 

and the LogItem list in my ViewModel:

  private ObservableCollection<LogItem> _logItems; public ObservableCollection<LogItem> LogItems { get { return _logItems; } set { if (value != _logItems) { _logItems = value; OnPropertyChanged("LogItems"); } } } 

My view model is view-bound, so I can do the following:

 <ListBox Grid.Row="0" Margin="0,10,0,0" Grid.ColumnSpan="3" Height="150" ItemsSource="{Binding LogItems}"> 

(Obviously, I still need to set the text display binding, etc.)

Question

Given that I have the Message and MessageColor in LogItems, what is the correct XAML syntax to associate the text color of an element with the specified color?

+8
c # wpf mvvm xaml listbox
source share
1 answer
  <ListBox Grid.Row="0" Margin="0,10,0,0" Grid.ColumnSpan="3" Height="150" ItemsSource="{Binding LogItems}"> <ListBox.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding Message}" Foreground="{Binding MessageColor}"/> </DataTemplate> </ListBox.ItemTemplate> </ListBox> 

TextBlock Foreground expects Brush not a Color . Like many things in WPF, there are many ways to do this. Here is a couple:

  • Change the MessageColor property in your MessageColor view to Brush

     Brush MessageColor {get;set;} 
  • Create a SolidColorBrush and bind it to a color

      <TextBlock Text="{Binding Message}"> <TextBlock.Foreground> <SolidColorBrush Color="{Binding MessageColor}"/> </TextBlock.Foreground> </TextBlock> 
  • Create a ColorToBrushConverter

     public class ColorToBrushConverter : IValueConverter { #region IValueConverter Members public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (value == null) return Brushes.Black; // Default color Color color = (Color)value; return new SolidColorBrush(color); } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } #endregion } 

In xaml, create a converter as a static resource

 <Window.Resources> <local:ColorToBrushConverter x:Key="colorToBrushConverter"/> </Window.Resources> 

use it in binding

 <TextBlock Text="{Binding Message}" Foreground="{Binding MessageColor, Converter={StaticResource colorToBrushConverter}"/> 

Good luck.

+21
source share

All Articles