wpf textblock中每4个字符后添加一个空格

时间:2019-12-27 15:41:59

标签: c# wpf 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"/>

我已经做到了,以便在写入文本框后将其键入文本块:

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

我要制作它,以便它在文本块中每4个字符添加一个空格,否则,如果它是文本框,则可以使用以下内容:

Insert hyphen automatically after every 4 characters in a TextBox

我该怎么做?

3 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

您可以这样创建一个Converter:

public class SeperatorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (targetType != typeof(string))
            throw new InvalidOperationException("The target must be a string");

        if (value != null)
        {
            var res = string.Join(" ",
                Enumerable.Range(0, value.ToString().Length / 4).Select(i => value.ToString().Substring(i * 4, 4)));

            return res;
        }

        return string.Empty;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

为此,您应该这样做:

     <Window.Resources>
    <local:SeperatorConverter x:Key="seperatorConverter"/>
</Window.Resources>
<StackPanel>
    <TextBox Name="TextBox1" Width="200"/>
    <TextBlock Text="{Binding ElementName=TextBox1,Path=Text,Converter={StaticResource seperatorConverter}}"/></StackPanel>

答案 2 :(得分:-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);