How to get rid of whitespace between Runs in TextBlock?

后端 未结 6 626
情深已故
情深已故 2020-12-08 01:39

I have following XAML:



        
6条回答
  •  时光取名叫无心
    2020-12-08 02:31

    I ported Pieter's attached property to WPF (I think it's for UWP).

    Example:

    
        
        
            Foo
            
            Baz
        
        
        
            Foo
            
            Baz
        
        
        
            Foo
            
            Baz
        
    
    

    using System;
    using System.Linq;
    using System.Text.RegularExpressions;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Documents;
    
    public class TextBlockHelper
    {
        public static bool GetTrimRuns(TextBlock textBlock) => (bool)textBlock.GetValue(TrimRunsProperty);
        public static void SetTrimRuns(TextBlock textBlock, bool value) => textBlock.SetValue(TrimRunsProperty, value);
    
        public static readonly DependencyProperty TrimRunsProperty =
            DependencyProperty.RegisterAttached("TrimRuns", typeof(bool), typeof(TextBlockHelper),
                new PropertyMetadata(false, OnTrimRunsChanged));
    
        private static void OnTrimRunsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var textBlock = d as TextBlock;
            textBlock.Loaded += OnTextBlockLoaded;
        }
    
        static void OnTextBlockLoaded(object sender, EventArgs args)
        {
            var textBlock = sender as TextBlock;
            textBlock.Loaded -= OnTextBlockLoaded;
    
            var runs = textBlock.Inlines.OfType().ToList();
            foreach (var run in runs)
                run.Text = TrimOne(run.Text);
        }
    
        private static string TrimOne(string text)
        {
            if (text.FirstOrDefault() == ' ')
                text = text.Substring(1);
            if (text.LastOrDefault() == ' ')
                text = text.Substring(0, text.Length - 1);
    
            return text;
        }
    }
    

提交回复
热议问题