C# WPF 绑定:根据属性设置列表框项文本颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18982150/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 13:47:22  来源:igfitidea点击:

WPF binding: Set Listbox Item text color based on property

c#wpfxamlmvvmlistbox

提问by SeanKilleen

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.

我确定这可能是 WPF 中的基本内容,但我是 XAML 语法的新手,我正试图围绕它展开。

The Setup

设置

I have a LogItemType -- just a POCO:

我有一个LogItem类型——只是一个 POCO:

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

and a List of LogItemin my ViewModel:

以及LogItem我的 ViewModel 中的列表:

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

My viewmodel is bound to the view so that 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 have to set the display text binding, etc.)

(显然我仍然需要设置显示文本绑定等)

The Question

问题

Given that I have a Messageand MessageColorproperty in LogItems, what is the correct XAML syntax to bind the color of the item text to the color I specify?

鉴于我在 LogItems 中有一个MessageandMessageColor属性,将项目文本的颜色绑定到我指定的颜色的正确 XAML 语法是什么?

采纳答案by Omri Btian

    <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 Foregroundexpects a Brushnot a Color. Like a lot of things in WPF, There are lot's of ways to approch this. Here is a couple:

TextBlockForeground需要一个Brushnot a Color。就像 WPF 中的很多东西一样,有很多方法可以解决这个问题。这是一对:

  1. Change to MessageColorproperty in your viewModel to Brush

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

      <TextBlock Text="{Binding Message}">
          <TextBlock.Foreground>
             <SolidColorBrush Color="{Binding MessageColor}"/>
          </TextBlock.Foreground>
      </TextBlock>
    
  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
    }
    
  1. MessageColor将 viewModel 中的属性更改为Brush

    Brush MessageColor {get;set;}
    
  2. 创建一个SolidColorBrush并将其绑定到您的颜色

      <TextBlock Text="{Binding Message}">
          <TextBlock.Foreground>
             <SolidColorBrush Color="{Binding MessageColor}"/>
          </TextBlock.Foreground>
      </TextBlock>
    
  3. 创建一个 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

在 xaml 中,将转换器创建为静态资源

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

use it in the binding

在绑定中使用它

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

Good luck

祝你好运