如何加粗绑定TextBlock的部分?

时间:2009-10-14 16:29:24

标签: c# wpf textblock bold

我有一个绑定到属性的TextBlock。但是,我想在文中强调某些词语。最简单的方法是什么?仅供参考,我是WPF的新手。

1 个答案:

答案 0 :(得分:6)

对单个单词进行粗体处理涉及实际创建更多内联元素,因此您不能将字符串绑定到TextBlock的Text并执行此操作。

我过去为此所做的是创建了一个TextBlock的子类,它有一个我绑定的自定义属性。当绑定此属性时,我清除基本TextBlock的内联,然后使用解析新字符串值的算法创建普通运行,粗体,超链接等。

这是我为实验性Twitter客户端编写的一些示例代码,它检测URL,电子邮件和@模式并为它们创建超链接。常规文本内联为正常运行:

[ContentProperty("StatusText")]
public sealed class StatusTextBlock : TextBlock
{
    #region Fields

    public static readonly DependencyProperty StatusTextProperty = DependencyProperty.Register(
                                                                                    "StatusText", 
                                                                                          typeof(string),
                                                                                    typeof(StatusTextBlock),
                                                                                    new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.None, StatusTextBlock.StatusTextPropertyChangedCallback, null));
    private static readonly Regex UriMatchingRegex = new Regex(@"(?<url>[a-zA-Z]+:\/\/[a-zA-Z0-9]+([\-\.]{1}[a-zA-Z0-9]+)*\.[a-zA-Z]{2,5}(:[0-9]{1,5})?([a-zA-Z0-9_\-\.\~\%\+\?\=\&\;\|/]*)?)|(?<emailAddress>[^\s]+@[a-zA-Z0-9]+([\-\.]{1}[a-zA-Z0-9]+)*\.[a-zA-Z]{2,5})|(?<toTwitterScreenName>\@[a-zA-Z0-9\-_]+)", RegexOptions.Compiled);

    #endregion

    #region Constructors

    public StatusTextBlock()
    {
    }

    #endregion

    #region Type specific properties

    public string StatusText
    {
        get
        {
            return (string)this.GetValue(StatusTextBlock.StatusTextProperty);
        }

        set
        {
            this.SetValue(StatusTextBlock.StatusTextProperty, value);
        }
    }

    #endregion

    #region Helper methods

    internal static IEnumerable<Inline> GenerateInlinesFromRawEntryText(string entryText)
    {
        int startIndex = 0;
        Match match = StatusTextBlock.UriMatchingRegex.Match(entryText);

        while(match.Success)
        {
            if(startIndex != match.Index)
            {
                yield return new Run(StatusTextBlock.DecodeStatusEntryText(entryText.Substring(startIndex, match.Index - startIndex)));
            }

            Hyperlink hyperLink = new Hyperlink(new Run(match.Value));

            string uri = match.Value;

            if(match.Groups["emailAddress"].Success)
            {
                uri = "mailto:" + uri;
            }
            else if(match.Groups["toTwitterScreenName"].Success)
            {
                uri = "http://twitter.com/" + uri.Substring(1);
            }

            hyperLink.NavigateUri = new Uri(uri);

            yield return hyperLink;

            startIndex = match.Index + match.Length;

            match = match.NextMatch();
        }

        if(startIndex != entryText.Length)
        {
            yield return new Run(StatusTextBlock.DecodeStatusEntryText(entryText.Substring(startIndex)));
        }
    }

    internal static string DecodeStatusEntryText(string text)
    {
        return text.Replace("&gt;", ">").Replace("&lt;", "<");
    }

    private static void StatusTextPropertyChangedCallback(DependencyObject target, DependencyPropertyChangedEventArgs eventArgs)
    {
        StatusTextBlock targetStatusEntryTextBlock = (StatusTextBlock)target;

        targetStatusEntryTextBlock.Inlines.Clear();

        string newValue = eventArgs.NewValue as string;

        if(newValue != null)
        {
            targetStatusEntryTextBlock.Inlines.AddRange(StatusTextBlock.GenerateInlinesFromRawEntryText(newValue));
        }
    }

    #endregion
}