如何使用附加属性在指定关键字的文本块中用粗体突出显示单词 [英] How to highlight the word(s) with bold in text block for specified keyword using the attached property

查看:17
本文介绍了如何使用附加属性在指定关键字的文本块中用粗体突出显示单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目标是使用匹配的输入关键字将 Textblock 中文本的单词加粗.

The objective is to bold the word(s) of text in Textblock with matching input keyword.

例如:Stackoverflow 非常有用,请继续使用 Stackoverflow 来磨练您的技能.

For example: Stackoverflow is a very helpful, keep using Stackoverflow to sharpen your skills.

当关键字是:Stackoverflow 时,它现在应该显示为

When the keyword is: Stackoverflow it should now display as

Stackoverflow 非常有用,请继续使用 Stackoverflow 来磨练您的技能.

Stackoverflow is a very helpful, keep using Stackoverflow to sharpen your skills.

我尝试使用附加属性来实现相同的目标.下面是相同的snap代码

I tried to achieve the same objective using attached property. Below is the snap code of the same

public class HighLightKeyWord : DependencyObject
{

    //This word is used to specify the word to highlight
    public static readonly DependencyProperty BoldWordProperty = DependencyProperty.RegisterAttached("BoldWord", typeof(string), typeof(HighLightKeyWord),
        new PropertyMetadata(string.Empty, OnBindingTextChanged));

    public static string GetBoldWord(DependencyObject obj)
    {
        return (string)obj.GetValue(BoldWordProperty);
    }

    public static void SetBoldWord(DependencyObject obj, string value)
    {
        obj.SetValue(BoldWordProperty, value);
    }

    private static void OnBindingTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {

        var _Key = e.NewValue as string;
        var textblk = d as TextBlock;
        string SourceText = textblk.Text;
        SetBold(_Key, textblk, SourceText);

    }

    private static void SetBold(string key, TextBlock text, string SourceText)
    {
        text.Inlines.Clear();
        var words = SourceText.Split(' ');
        for (int i = 0; i < words.Length; i++)
        {
            var word = words[i];
            var inline = new Run() { Text = word + ' ' };
            if (String.Compare(word, key,  StringComparison.CurrentCultureIgnoreCase) == 0)
            {
                inline.FontWeight = FontWeights.Bold;
            }
            text.Inlines.Add(inline);
        }
    }

}

//在 Main 中绑定对象

// Bind object in Main

        StackOverFlow stkovrflw = new StackOverFlow();
        stkovrflw.Text    = "Stackoverflow is a very helpful,keep using Stackoverflow to sharpen your skills.";
        stkovrflw.KeyWord = "Stackoverflow";
        this.DataContext = stkovrflw;

在 Xaml 中,我将值绑定为

In Xaml I binded the value as

<TextBlock Text="{Binding Path=Text}"  loc:HighLightKeyWord.BoldWord="{Binding Path=KeyWord}" />

上面的代码工作正常,但是当我直接在 xaml 中设置 HighlightText 属性而不是通过数据绑定时,Text 块的 Text 属性在 OnBindingTextChanged 方法中变空,并且此方法仅在设置依赖项属性时调用一次.我使用基于 Spellchecker 概念的这个设计,以便其他团队可以在他们的项目中重用我的附加属性.任何人都可以建议如何解决问题?

Above code is working fine, however when I directly sets the HighlightText property in the xaml instead through data binding, Text property of the Text block is getting empty in the OnBindingTextChanged method and this method is called only once when dependency property is set . I used this design based on Spellchecker concept so that other teamates can reuse my attached property in their projects. Can anyone suggest how to fix the problem?

推荐答案

无论您是要修改 TextBlock 的 FontWeight 属性还是其他显示属性,我都编写了以下静态方法并发现它非常有用.(注意:该方法通过修改 Foreground 属性来说明突出显示文本.相同的原理可用于任何其他 TextBlock 显示属性.)

Whether you want to modify a TextBlock FontWeight attribute or another display property, I've written the following static method and found it very useful. (Note: The method illustrates highlighting text by modifying the Foreground property. The same principle can be used for any other TextBlock display attribute.)

    static Brush DefaultHighlight = new SolidColorBrush(Colors.Red);

    public static void SetTextAndHighlightSubstring(this TextBlock targetTextBlock, string sourceText, string subString, Brush highlight = null)
    {
        if (targetTextBlock == null || String.IsNullOrEmpty(sourceText) || String.IsNullOrEmpty(subString))
            return;
        targetTextBlock.Text = "";
        var subStringPosition = sourceText.ToUpper().IndexOf(subString);
        if (subStringPosition == -1)
        {
            targetTextBlock.Inlines.Add(new Run { Text = sourceText });
            return;
        }
        var subStringLength = subString.Length;
        var header = sourceText.Substring(0, subStringPosition);
        subString = sourceText.Substring(subStringPosition, subStringLength);
        var trailerLength = sourceText.Length - (subStringPosition + subStringLength);
        var trailer = sourceText.Substring(subStringPosition + subStringLength, trailerLength);
        targetTextBlock.Inlines.Add(new Run { Text = header });
        targetTextBlock.Inlines.Add(new Run { Text = subString, Foreground = highlight ?? DefaultHighlight });
        targetTextBlock.Inlines.Add(new Run { Text = trailer });
    }

您可以使用 TextBlock 扩展语法调用此方法,如下所示:

You can call this method using the TextBlock extension syntax like so:

TextBlockTitle.SetTextAndHighlightSubstring(_categoryItem.ItemText, _searchText);

在本例中,结果如下:

这篇关于如何使用附加属性在指定关键字的文本块中用粗体突出显示单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆