简体   繁体   中英

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?

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

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

You can create a Converter like this:

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();
    }
}

And for use this you should do this:

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

Try following :

           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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM