How to bind a TextBlock to a resource containing formatted text?

前端 未结 7 907
被撕碎了的回忆
被撕碎了的回忆 2020-11-28 08:57

I have a TextBlock in my WPF window.

 
     Some formatted text.
 

When it is r

相关标签:
7条回答
  • 2020-11-28 09:32

    This work for me:

    XAML:

    <phone:PhoneApplicationPage x:Class="MyAPP.Views.Class"
                            xmlns:utils="clr-namespace:MyAPP.Utils">
    

    and your TextBlock XAML:

    <TextBlock utils:TextBlockHelper.FormattedText="{Binding Text}" />
    

    CODE:

    public static class TextBlockHelper
    {
        public static string GetFormattedText(DependencyObject textBlock)
        { 
            return (string)textBlock.GetValue(FormattedTextProperty); 
        }
    
        public static void SetFormattedText(DependencyObject textBlock, string value)
        { 
            textBlock.SetValue(FormattedTextProperty, value); 
        }
    
        public static readonly DependencyProperty FormattedTextProperty =
            DependencyProperty.RegisterAttached("FormattedText", typeof(string), typeof(TextBlock),
            new PropertyMetadata(string.Empty, (sender, e) =>
            {
                string text = e.NewValue as string;
                var textB1 = sender as TextBlock;
                if (textB1 != null)
                {
                    textB1.Inlines.Clear();
                    var str = text.Split(new string[] { "<b>", "</b>" }, StringSplitOptions.None);
                    for (int i = 0; i < str.Length; i++)
                        textB1.Inlines.Add(new Run { Text = str[i], FontWeight = i % 2 == 1 ? FontWeights.Bold : FontWeights.Normal });
    
                }
            }));
    }
    

    USE in your string binding:

    String Text = Text <b>Bold</b>;
    
    0 讨论(0)
提交回复
热议问题