c# - 如何将绑定(bind)的 TextBlock 的部分加粗?

标签 c# wpf textblock bold

我有一个绑定(bind)到属性的 TextBlock。但是,我想将文本中的某些词加粗。最简单的方法是什么?仅供引用,我是 WPF 的新手。

最佳答案

加粗单个单词实际上涉及创建更多内联元素,因此您不能只将字符串绑定(bind)到 TextBlock 的文本并执行此操作。

我过去为此所做的是创建一个 TextBlock 的子类,它具有我绑定(bind)的自定义属性。当这个属性被绑定(bind)时,我清除了基本 TextBlock 的内联,然后使用一个算法来解析新的字符串值,创建普通的 Runs、Bolds、Hyperlinks 等。

这是我为我的实验性 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
}

关于c# - 如何将绑定(bind)的 TextBlock 的部分加粗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1567449/

相关文章:

c# - 一个用于 UserControl 和 Window 的 ViewModel 或单独的 ViewModel

c# - 在 WPF TextBlock 中显示 XAML 格式的文本

wpf - 如何将 IsSelected 属性绑定(bind)到文本 block

wpf - 数据绑定(bind) TextBlock.Inlines

c# - 这是处理 SQLConnection 的正确方法吗

c# - .Net PropertyGrid DropDownList - 返回值不同于显示值

c# - 使用递归函数遍历 XML

c# - 如何在运行时移除/删除图片框?

wpf - 如何在没有 AttachedProperty 或 DependencyProperty 的情况下使用 IDataErrorInfo 验证密码框?

c# - 我可以在 WPF 中捕获对可观察结构成员的更新吗?