更改标签中某些字符串的前景色

时间:2016-03-18 10:22:11

标签: c# wpf colors

我想知道是否可以在以下编码中更改字符串item.Name的前景色,而字符串的其余部分保留我在标签中设置的默认颜色' s XAML中的前景色设置。

lblLoggedInUser.Content = "Logged in:  " + item.Name + " " + item.Surname;

我希望item.Name具有与字符串其余部分不同的颜色。有可能吗?

3 个答案:

答案 0 :(得分:1)

为此,我创建了一个带附加属性的辅助类。

public class HighlightHelper : DependencyObject
{
    public static Brush GetHighlightBrush(DependencyObject obj)
    {
        return (Brush)obj.GetValue(HighlightBrushProperty);
    }
    public static void SetHighlightBrush(DependencyObject obj, Brush value)
    {
        obj.SetValue(HighlightBrushProperty, value);
    }
    public static readonly DependencyProperty HighlightBrushProperty =
        DependencyProperty.RegisterAttached("HighlightBrush", typeof(Brush), typeof(HighlightHelper), new PropertyMetadata(Brushes.Black));

    public static string GetHighlightWord(UIElement element)
    {
        return (string)element.GetValue(HighlightWordProperty);
    }
    public static void SetHighlightWord(UIElement element, string value)
    {
        element.SetValue(HighlightWordProperty, value);
    }
    public static readonly DependencyProperty HighlightWordProperty =
        DependencyProperty.RegisterAttached("HighlightWord", typeof(string), typeof(HighlightHelper), new PropertyMetadata(OnHighlightWordChanged));

    private static void OnHighlightWordChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        TextBlock textBlock = (TextBlock)d;
        string text = textBlock.Text;
        string highlightWord = (string)e.NewValue;

        textBlock.Inlines.Clear();

        string[] tokens = Regex.Split(text, "(" + Regex.Escape(highlightWord) + ")");

        foreach (string token in tokens)
        {
            Run run = new Run { Text = token };

            if (token.Equals(highlightWord))
            {
                Brush highlightBrush = (Brush)textBlock.GetValue(HighlightBrushProperty);
                run.Foreground = highlightBrush;
            }

            textBlock.Inlines.Add(run);
        }
    }
}

你可以像这样使用它:

<TextBlock Text="{Binding DisplayText}" Foreground="Red"
            local:HighlightHelper.HighlightWord="{Binding TextToHighlight}"
            local:HighlightHelper.HighlightBrush="Blue"></TextBlock>

答案 1 :(得分:0)

我认为一种方法是使用包含StackPanel的水平LabelForeground属性设置为不同的颜色。例如:

<StackPanel>
  <StackPanel Orientation="Horizontal">
    <Label VerticalAlignment="Center" Foreground="#000000">Logged in: </Label>
    <Label VerticalAlignment="Center" Foreground="#FFFFFF"></Label>
  </StackPanel>
</StackPanel>

答案 2 :(得分:0)

您可以使用以下内容:

    <TextBlock>
        <Run Text="Logged in" />
        <Run Text="{Binding Name}" Foreground="Blue" />
        <Run Text="{Binding Surname}" />
    </TextBlock>
相关问题