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 10 0” TextValue=“가나다라마바사” />
==========결과물==========
WPF TextBlock에서 Text 자간 조절 질문이 있길래 간단하게 만들어봤습니다.
잘못된점이나 더 좋은 코드가 있으면 환영입니다.