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

前端 未结 7 953
被撕碎了的回忆
被撕碎了的回忆 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:23

    The same I have implemented using Behavior. Code given below:

    public class FormatTextBlock : Behavior
    {
        public static readonly DependencyProperty FormattedTextProperty = 
            DependencyProperty.Register(
                "FormattedText", 
                typeof(string),
                typeof(FormatTextBlock),
                new PropertyMetadata(string.Empty, OnFormattedTextChanged));
    
        public string FormattedText
        {
            get { return (string)AssociatedObject.GetValue(FormattedTextProperty); }
            set { AssociatedObject.SetValue(FormattedTextProperty, value); }
        }
    
        private static void OnFormattedTextChanged(DependencyObject textBlock, DependencyPropertyChangedEventArgs eventArgs)
        {
            System.Windows.Controls.TextBlock currentTxtBlock = (textBlock as FormatTextBlock).AssociatedObject;
    
            string text = eventArgs.NewValue as string;
    
            if (currentTxtBlock != null)
            {
                currentTxtBlock.Inlines.Clear();
    
                string[] strs = text.Split(new string[] { "", "" }, StringSplitOptions.None);
    
                for (int i = 0; i < strs.Length; i++)
                {
                    currentTxtBlock.Inlines.Add(new Run { Text = strs[i], FontWeight = i % 2 == 1 ? FontWeights.Bold : FontWeights.Normal });
                }
            }
        }
    }
    

    XAML - import namespace

    
    

    Then to use the behavior as:

        
            
                
            
        
    

提交回复
热议问题