Search code examples
c#wpftextblock

Add a space after every 4 characters in textblock wpf


I have a card textblock that I am using to show the user the card number:

<TextBlock x:Name="ccCard" Text="0000 0000 0000 0000" HorizontalAlignment="Center" 
Foreground="LightGray" FontFamily="Global Monospace" Grid.ColumnSpan="4" Margin="0,0,0,0.4" Width="200"/>

I have made it so that when a textbox has been written in, it types it into the textblock:

<TextBlock x:Name="ccCard" Text="0000 0000 0000 0000" HorizontalAlignment="Center" 
Foreground="LightGray" FontFamily="Global Monospace" Grid.ColumnSpan="4" Margin="0,0,0,0.4" 
Width="200"/>

I want to make it so it adds a space every 4 characters in the textblock, otherwise if it was a textbox I could use something like this:

Insert hyphen automatically after every 4 characters in a TextBox

How would I be able to do this?


Solution

  • For anyone wondering, as suggested by Çöđěxěŕ, the answer would look something like this:

    ccCard.Text = string.Join(" ", Enumerable.Range(0, txtBox.Text.Length / 4).Select(i => txtBox.Text.Substring(i * 4, 4)));