WPF binding: Set Listbox Item text color based on property

前端 未结 1 1337
庸人自扰
庸人自扰 2020-12-10 15:37

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.

The Setup

I have a LogItem

1条回答
  •  臣服心动
    2020-12-10 16:33

        
            
                
                    
                
            
        
    

    TextBlock Foreground expects a Brush not a Color. Like a lot of things in WPF, There are lot's of ways to approch this. Here is a couple:

    1. Change to MessageColor property in your viewModel to Brush

      Brush MessageColor {get;set;}
      
    2. Create a SolidColorBrush and bind it to your color

        
            
               
            
        
      
    3. 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 the converter as static resource

    
        
    
    

    use it in the binding

    
    

    Good luck

    0 讨论(0)
提交回复
热议问题