Created
September 22, 2022 13:47
-
-
Save LGM-AdrianHum/85c0e62c0ca38606b3009b25373143bb to your computer and use it in GitHub Desktop.
An extension for textblocks in WPF to get rid of annoying spaces between runs.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ---------------------------------------------------------------------------------- | |
// <copyright file="TextBlockExtension.cs" > | |
// This file is part of the MyS3Uploader distribution | |
// | |
// Copyright (c) 2022 | |
// | |
// This program is distributed WITHOUT ANY WARRANTY; without even the implied | |
// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. | |
// </copyright> | |
// <summary> | |
// <developer>Casandra/Adrian Hum</developer> | |
// <solution>MyS3Uploader/S3Commander/TextBlockExtension.cs</solution> | |
// <created>2022-09-22 11:09 PM</created> | |
// <modified>2022-09-22 11:44 PM</modified> | |
// <usage>local:TextBlockExtension.RemoveEmptyRuns="True" in the TextBlock tag.</usage> | |
// </summary> | |
// ---------------------------------------------------------------------------------- | |
using System; | |
using System.Linq; | |
using System.Windows; | |
using System.Windows.Controls; | |
using System.Windows.Documents; | |
namespace CommonFunctions { | |
public class TextBlockExtension { | |
public static readonly DependencyProperty RemoveEmptyRunsProperty = | |
DependencyProperty.RegisterAttached("RemoveEmptyRuns", typeof(bool), | |
typeof(TextBlock), new PropertyMetadata(false)); | |
public static readonly DependencyProperty PreserveSpaceProperty = | |
DependencyProperty.RegisterAttached("PreserveSpace", typeof(bool), | |
typeof(Run), new PropertyMetadata(false)); | |
public static bool GetRemoveEmptyRuns(DependencyObject obj) { | |
return (bool) obj.GetValue(RemoveEmptyRunsProperty); | |
} | |
public static void SetRemoveEmptyRuns(DependencyObject obj, bool value) { | |
obj.SetValue(RemoveEmptyRunsProperty, value); | |
if (value) | |
{ | |
if (obj is TextBlock tb) | |
tb.Loaded += Tb_Loaded; | |
else | |
throw new NotSupportedException(); | |
} | |
} | |
public static bool GetPreserveSpace(DependencyObject obj) { | |
return (bool) obj.GetValue(PreserveSpaceProperty); | |
} | |
public static void SetPreserveSpace(DependencyObject obj, bool value) { | |
obj.SetValue(PreserveSpaceProperty, value); | |
} | |
private static void Tb_Loaded(object sender, RoutedEventArgs e) { | |
var tb = sender as TextBlock; | |
tb.Loaded -= Tb_Loaded; | |
var spaces = tb.Inlines.Where(a => a is Run | |
&& ((Run) a).Text == " " | |
&& !GetPreserveSpace(a)).ToList(); | |
spaces.ForEach(s => tb.Inlines.Remove(s)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment