在文本块wpf中每4个字符后添加一个空格

问题描述 投票:0回答:2

我有一个卡文本块,用于向用户显示卡号:

<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"/>

我这样做是为了在写入文本框后将其键入到文本块中:

<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"/>

我想制作它,所以它在textblock中每4个字符添加一个空格,否则,如果它是一个文本框,我可以使用类似这样的内容:

Insert hyphen automatically after every 4 characters in a TextBox

我将如何做到这一点?

c# wpf textblock
2个回答
0
投票

对于任何想知道的人,正如Çöđěxěŕ所建议的那样,答案看起来像这样:

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

-1
投票

尝试以下内容:

           string input = "0123456789012345678901234567890";
           string[] split = input.Select((x, i) => new { chr = x, index = i })
                .GroupBy(x => x.index / 4)
                .Select(x => string.Join("", x.Select(y => y.chr).ToArray()))
                .ToArray();
           string results = string.Join(" ", split);
© www.soinside.com 2019 - 2024. All rights reserved.