加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – XAML将文本块文本转换为内联

发布时间:2020-12-15 23:29:05 所属栏目:百科 来源:网络整理
导读:我想在UWP项目中的TextBlock上设置这种文本: "Bold" + variable + "/Bold" 但是将其设置为Text值不考虑 Bold标签. 所以我搜索了如何做,唯一的答案是“创建内联并将其添加到您的textBlock”. 但我不想在我的视图模型上这样做. 所以我正在寻找一个转换器来替
我想在UWP项目中的TextBlock上设置这种文本:

"<Bold>" + variable + "</Bold>"

但是将其设置为Text值不考虑< Bold>标签.

所以我搜索了如何做,唯一的答案是“创建内联并将其添加到您的textBlock”.
但我不想在我的视图模型上这样做.

所以我正在寻找一个转换器来替换我的text属性,通过inline集合来设置我的textBlock.
我找到了一些示例(https://social.msdn.microsoft.com/Forums/en-US/1a1af975-e186-4167-b1c9-cc86afcdd93a/how-to-show-text-in-textblock-as-rich-text-format?forum=wpf),但没有使用通用Windows应用程序(UWP).

我试过这个,但我有一个错误(无法将Binding强制转换为字符串):

<TextBlock  x:Name="newsArticleSections"
                            Tag="{Binding RelativeSource={RelativeSource Self},Mode=OneWay,Converter={StaticResource TextToRunConverter},ConverterParameter={Binding ArticleSections}}"/>

这是我的转换器:

public object Convert(object value,Type targetType,object parameter,string language)
    {
        TextBlock textblock = value as TextBlock;

        textblock.ClearValue(TextBlock.TextProperty);
        Run run = new Run();
        run.Text = (string)parameter;
        textblock.Inlines.Add(run);
        return null;
    }

这只是我探索的方式,但暂时没有结果.
有人有另一个想法吗?

解决方法

@devuxer回答是一个好主意,但仅适用于WPF项目.
所以我用它来制作UWP解决方案并且它有效:

创建一个Formatter类:

public class TextBlockFormatter
{
    public static readonly DependencyProperty FormattedTextProperty = DependencyProperty.RegisterAttached(
    "FormattedText",typeof(string),typeof(TextBlockFormatter),new PropertyMetadata(null,FormattedTextPropertyChanged));

    public static void SetFormattedText(DependencyObject textBlock,string value)
    {
        textBlock.SetValue(FormattedTextProperty,value);
    }

    public static string GetFormattedText(DependencyObject textBlock)
    {
        return (string)textBlock.GetValue(FormattedTextProperty);
    }

    private static void FormattedTextPropertyChanged(DependencyObject d,DependencyPropertyChangedEventArgs e)
    {
        // Clear current textBlock
        TextBlock textBlock = d as TextBlock;
        textBlock.ClearValue(TextBlock.TextProperty);
        textBlock.Inlines.Clear();
        // Create new formatted text
        string formattedText = (string)e.NewValue ?? string.Empty;
        string @namespace = "http://schemas.microsoft.com/winfx/2006/xaml/presentation";
        formattedText = $@"<Span xml:space=""preserve"" xmlns=""{@namespace}"">{formattedText}</Span>";
        // Inject to inlines
        var result = (Span)XamlReader.Load(formattedText);
        textBlock.Inlines.Add(result);
    }

}

并将此引用添加到您的XAML文件:

xmlns:helpers="using:MyProject.Helpers"

要使用格式化程序,只需添加一个TextBlock并在FormattedText上声明您的绑定,如下所示:

<TextBlock  x:Name="textBlock" helpers:TextBlockFormatter.FormattedText="{Binding Content}">

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读