我有一个WPF应用程序来显示一些LogMessage列表。 LogMessage类如下所示:
public class LogMessage
{
public DateTime Timestamp { get; set; }
public LogLevel LogLevel { get; set; }
public string Message { get; set; }
}
我想使用此ValueConverter将LogLevel
的值绑定到Foreground
的{{1}}属性:
TextBlock
该视图看起来像这样:
[ValueConversion(typeof(LogLevel), typeof(Brush))]
public class LogLevelToColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var logLevel = (LogLevel)value;
switch (logLevel)
{
case LogLevel.Info:
return new SolidColorBrush(Colors.DarkGray);
case LogLevel.Important:
return new SolidColorBrush(Colors.Green);
case LogLevel.Warning:
return new SolidColorBrush(Colors.Orange);
case LogLevel.Error:
return new SolidColorBrush(Colors.Red);
default:
return new SolidColorBrush(Colors.DarkGray);
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
我的问题是我的值转换器中的<Window x:Class="TouchLogic.EcrServer.Wpf.Views.MainView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:TouchLogic.EcrServer.Wpf.ViewModels"
mc:Ignorable="d"
Title="MainView" Height="450" Width="800">
<Window.Resources>
<local:LogLevelToColorConverter x:Key="LogLevelToColorConverter"/>
</Window.Resources>
<Grid Margin="8">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="140" />
</Grid.ColumnDefinitions>
<ListBox Grid.Row="0" Grid.Column="0" ItemsSource="{Binding LogMessages}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Timestamp}" Foreground="{Binding LogLevel, Converter={StaticResource LogLevelToColorConverter}}"/>
<TextBlock Text="{Binding Message}" Foreground="{Binding LogLevel, Converter={StaticResource LogLevelToColorConverter}}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Window>
总是以value
的形式出现,我不知道为什么。