ListView字符串部分字体为彩色

时间:2019-02-14 07:14:18

标签: c# wpf listview colors

我有一个类似的ListView:

 <ListView  Name="myLV"  ItemsSource="{Binding myObservableCollection}" IsSynchronizedWithCurrentItem="True" >
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="v1" Width="150">
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <TextBlock Text="{Binding var1}"/>
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>
                    <GridViewColumn Header="v2" Width="150">
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <TextBlock Text="{Binding var2}"/>
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>
                    <GridViewColumn Header="v3" Width="150">
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <TextBlock Text="{Binding var3}"/>
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>
                </GridView>
            </ListView.View>
        </ListView>

每行都有一组三个字符串,例如:

  • 字符串1:aa-bbbb-cc
  • 字符串2:ax-bbbb-cd
  • 字符串3:aa-bbbb-ce

现在,我想为三个字符串分别在不同位置上使用单独的文本颜色。在上面的示例中,我将必须为三个字符串的第二个和第十个位置上色。

我不知道如何开始执行此任务,因为对我来说,搜索该问题甚至非常困难。有想法吗?

1 个答案:

答案 0 :(得分:1)

您可以创建一个用户控件,该控件将文本分为四个部分,并允许您独立设置样式。以下示例控件将文本作为输入,并将零件存储在专用属性中:

public partial class MyFormattedTextControl : UserControl, INotifyPropertyChanged
{
    public MyFormattedTextControl()
    {
        InitializeComponent();
        stack.DataContext = this;
    }

    public string Text
    {
        get { return (string)GetValue(TextProperty); }
        set { SetValue(TextProperty, value); }
    }

    // Using a DependencyProperty as the backing store for Text.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty TextProperty =
        DependencyProperty.Register("Text", typeof(string), typeof(MyFormattedTextControl), new PropertyMetadata(null, OnTextPropertyChanged));

    private static void OnTextPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var ctrl = (MyFormattedTextControl)d;
        var t = (string)e.NewValue;
        var regex = new Regex("(?<Part1>.)(?<Part2>.)(?<Part3>.{7})(?<Part4>.)");
        var m = regex.Match(t);
        if (!m.Success)
        {
            ctrl.Part1 = ctrl.Part2 = ctrl.Part3 = ctrl.Part4 = string.Empty;
        }
        else
        {
            ctrl.Part1 = m.Groups["Part1"].Value;
            ctrl.Part2 = m.Groups["Part2"].Value;
            ctrl.Part3 = m.Groups["Part3"].Value;
            ctrl.Part4 = m.Groups["Part4"].Value;
        }
    }

    private string part1;

    public string Part1
    {
        get { return part1; }
        set { part1 = value; OnPropertyChanged(); }
    }

    private string part2;

    public string Part2
    {
        get { return part2; }
        set { part2 = value; OnPropertyChanged(); }
    }


    private string part3;

    public string Part3
    {
        get { return part3; }
        set { part3 = value; OnPropertyChanged(); }
    }

    private string part4;

    public string Part4
    {
        get { return part4; }
        set { part4 = value; OnPropertyChanged(); }
    }

    private void OnPropertyChanged([CallerMemberName] string callerMember = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(callerMember));
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

在XAML文件中,用户控件将零件显示在单独的文本块中,您可以独立设置样式:

<StackPanel x:Name="stack" Orientation="Horizontal">
    <TextBlock Text="{Binding Part1}" />
    <TextBlock Text="{Binding Part2}" Foreground="Red" />
    <TextBlock Text="{Binding Part3}" />
    <TextBlock Text="{Binding Part4}" Foreground="Green" />
</StackPanel>

在ListView中,您使用用户控件而不是TextBlock:

<DataTemplate>
  <local:MyFormattedTextControl Text="{Binding var1}" />
</DataTemplate>

更新:根据数据值格式化块

为了向模式提供行值,您可以向用户控件添加另一个依赖项属性:

public IEnumerable<bool> PartFlags
{
    get { return (bool[])GetValue(PartFlagsProperty); }
    set { SetValue(PartFlagsProperty, value); }
}

// Using a DependencyProperty as the backing store for PartFlags.  This enables animation, styling, binding, etc...
public static readonly DependencyProperty PartFlagsProperty =
    DependencyProperty.Register("PartFlags", typeof(bool[]), typeof(MyFormattedTextControl), new PropertyMetadata(new bool[] { false, false, false, false }));

为了将布尔值转换为颜色,您可以创建一个自定义值转换器,例如

public class PartColorValueConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var b = value as bool[] ?? new bool[] { };
        var i = System.Convert.ToInt32(parameter);
        return b.ElementAtOrDefault(i) ? Brushes.Red : Brushes.Black;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

您可以在用户控件中使用此转换器将颜色应用于部件:

<UserControl x:Class="MyWpfApp.MyFormattedTextControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:MyWpfApp"
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800">
    <UserControl.Resources>
        <local:PartColorValueConverter x:Key="partColorValueConv" />
    </UserControl.Resources>
    <StackPanel x:Name="stack" Orientation="Horizontal">
        <TextBlock Text="{Binding Part1}" Foreground="{Binding PartFlags, Converter = {StaticResource partColorValueConv}, ConverterParameter=0}" />
        <TextBlock Text="{Binding Part2}" Foreground="{Binding PartFlags, Converter = {StaticResource partColorValueConv}, ConverterParameter=1}" />
        <TextBlock Text="{Binding Part3}" Foreground="{Binding PartFlags, Converter = {StaticResource partColorValueConv}, ConverterParameter=2}" />
        <TextBlock Text="{Binding Part4}" Foreground="{Binding PartFlags, Converter = {StaticResource partColorValueConv}, ConverterParameter=3}" />
    </StackPanel>
</UserControl>

为了测试,我向包含模式(在我的情况下是随机生成的模式)的元组中添加了第四个值:

<local:MyFormattedTextControl Text="{Binding Item1}" PartFlags="{Binding Item4}" />