본문 바로가기
개발/C#(WPF)

WPF TextBlock에서 Text 자간 조절

by Piaso 2021. 8. 12.
public class CharacterSpacingTextBlock : TextBlock
{
 	public static readonly DependencyProperty SpacingProperty =
 	    DependencyProperty.Register(nameof(Spacing), typeof(Thickness), typeof(CharacterSpacingTextBlock), new PropertyMetadata(new Thickness(0), new PropertyChangedCallback(SpacingPropertyChanged)));
 	public Thickness Spacing
 	{
 	    get { return (Thickness)GetValue(SpacingProperty); }
 	    set { SetValue(SpacingProperty, value); }
 	}

 	public static readonly DependencyProperty TextValueProperty =
 	            DependencyProperty.Register(nameof(TextValue), typeof(string), typeof(CharacterSpacingTextBlock), new PropertyMetadata(string.Empty, new PropertyChangedCallback(TextValuePropertyChanged)));
 	public string TextValue
 	{
 	    get { return (string)GetValue(TextValueProperty); }
 	    set { SetValue(TextValueProperty, value); }
 	}

 	private static void SpacingPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
 	{
 	    if (d is CharacterSpacingTextBlock textblock)
 	    {
 	        SetSpacing(textblock);
 	    }
 	}

 	private static void TextValuePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
 	{
 	    if (d is CharacterSpacingTextBlock textblock)
 	    {
 	        SetSpacing(textblock);
 	    }
 	}

 	private static void SetSpacing(CharacterSpacingTextBlock characterSpacingTextBlock)
 	{
 	    if (!string.IsNullOrEmpty(characterSpacingTextBlock.TextValue))
 	    {
 	        characterSpacingTextBlock.Text = string.Empty;
 	        foreach (var character in characterSpacingTextBlock.TextValue.ToCharArray())
 	        {
 	            var addTextBlock = new TextBlock();
 	            addTextBlock.Margin = new Thickness(characterSpacingTextBlock.Spacing.Left, characterSpacingTextBlock.Spacing.Top, characterSpacingTextBlock.Spacing.Right, characterSpacingTextBlock.Spacing.Bottom);
 	            addTextBlock.Text = character.ToString();
 	            characterSpacingTextBlock.Inlines.Add(addTextBlock);
 	        }
 	    }
 	}
}

 

 

 

================사용법================

<local:CharacterSpacingTextBlock Spacing="0 0 20 0" TextValue="가나다라마바사" />

 

================결과물================

간격조절된 결과물