设置TextBlock的内容

时间:2014-09-17 16:54:56

标签: wpf textblock

假设我有TextBlock,如下所示:

<TextBlock TextWrapping="Wrap" >
    Text in <Run Foreground="Red">red</Run> and <Run Foreground="Red">more</Run>
</TextBlock>

工作正常,文字以红色显示,如您所愿。但是,在我的实例中这个文字:

 Text in <Run Foreground="Red">red</Run> and <Run Foreground="Red">more</Run>

来自服务电话。 (包括标签。)

有没有办法在运行时向TextBlock提供此文字?

2 个答案:

答案 0 :(得分:2)

实际上,您必须将所有输入文本转换为Inlines集合(类型TextElementCollection)。但是这样做需要自己解析输入文本,这并不容易。那么为什么不使用XamlReader支持的现有解析器呢?通过使用此类,您可以解析XAML代码以获取TextBlock的实例,您可以从中获取Inlines集合并为实际TextBlock添加该集合。这是代码:

var text = "<TextBlock>Text in <Run Foreground=\"Red\">red</Run> and <Run Foreground=\"Red\">more</Run></TextBlock>";
var pc = new System.Windows.Markup.ParserContext();
pc.XmlnsDictionary[""] = "http://schemas.microsoft.com/winfx/2006/xaml/presentation";
pc.XmlnsDictionary["x"] = "http://schemas.microsoft.com/winfx/2006/xaml";
var tbl = System.Windows.Markup.XamlReader.Parse(text, pc) as TextBlock;
yourTextBlock.Inlines.Clear();            
yourTextBlock.Inlines.AddRange(tbl.Inlines.ToList());

您的实际输入文字应包含在<TextBlock>&amp;对中。在被下一个代码使用之前</TextBlock>

答案 1 :(得分:2)

我以为我会发布我对金刚答案的控制。 (以防它对其他人有用。)

public class FormatBindableTextBlock : TextBlock
{
    private static readonly ParserContext parserContext;

    static FormatBindableTextBlock()
    {
        parserContext = new System.Windows.Markup.ParserContext();
        parserContext.XmlnsDictionary[""] = "http://schemas.microsoft.com/winfx/2006/xaml/presentation";
        parserContext.XmlnsDictionary["x"] = "http://schemas.microsoft.com/winfx/2006/xaml";
    }

    public static readonly DependencyProperty FormattedContentProperty =
        DependencyProperty.Register("FormattedContent", typeof(string), typeof(FormatBindableTextBlock), new UIPropertyMetadata(null, OnFormattedContentPropertyChanged));

    public string FormattedContent
    {
        get { return (string)GetValue(FormattedContentProperty); }
        set { SetValue(FormattedContentProperty, value); }
    }

    private static void OnFormattedContentPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        FormatBindableTextBlock textBlock = sender as FormatBindableTextBlock;

        if (textBlock == null)
            return;

        string newFormattedContent = e.NewValue as string;
        if (string.IsNullOrEmpty(newFormattedContent)) 
            newFormattedContent = "";

        newFormattedContent = "<TextBlock>" + newFormattedContent + "</TextBlock>";

        TextBlock tbl = System.Windows.Markup.XamlReader.Parse(newFormattedContent, parserContext) as TextBlock;
        textBlock.Inlines.Clear();
        textBlock.Inlines.AddRange(tbl.Inlines.ToList());

    }

}