string.Format - 在两列中格式化两个变量

string.Format - format two variables in two columns

我正在开发一款应用,需要帮助。 在这个应用程序中,有一个列表框,其中将显示所有用户(类似于记分牌)。在用户的 ToString() 方法中,我将 string.Format 设置为 return 两个变量(姓名和金钱)。 但是当我 运行 那个应用程序时,我得到这样的输出:

bustercze   147
JohnyPrcina  158
anotherPlayer  47

但我希望输出是这样的:

bustercze       147
JohnyPrcina     158
anotherPlayer   47

希望你没看错。并且你可以帮助我。

我的 ToString() 代码:

public override string ToString()
    {
        return string.Format("{0}   {1}", Jmeno, Penize);
    }

我已经尝试过的: 1. http://www.csharp-examples.net/align-string-with-spaces/(没有帮助) 2. Format a string into columns(也没有帮助)

使用这种格式:"{0, -13} {1}"

注意:您可能希望将 13 更改为 20 或 25,这取决于 Jmeno 可以获得多长时间。


编辑:如果您在列表框中显示它,您需要使用等宽字体:

在下方添加此行 InitializeComponent(),或 before/after 填充数据:

listbox.Font = new Font(FontFamily.GenericMonospace, listbox.Font.Size);

不要使用 ToString() 来执行此操作。在您的 WPF 列表框中使用这样的模板

    <ListBox ItemsSource="{Binding Scores}" Grid.IsSharedSizeScope="True">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="Auto" SharedSizeGroup="JmenoColumn"/>
                        <ColumnDefinition Width="Auto" SharedSizeGroup="PenizeColumn"/>
                    </Grid.ColumnDefinitions>
                    <TextBlock Grid.Column="0" Margin="0,0,10,0" Text="{Binding Jmeno}"/>
                    <TextBlock Grid.Column="1" Text="{Binding Penize}"/>
                </Grid>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

那么你可以得到这个:

旧答案。(解决 ToString() 问题) 使用 PadRight,例如,

string.Format("{0}{1}", Jmeno.PadRight(20), Penize)

密码

int padding = 15;
string Jmeno = "bustercze";
int Penize = 147;
Console.WriteLine(string.Format("{0}{1}", Jmeno.PadRight(padding), Penize));
Jmeno = "JohnyPrcina";
Penize = 158;
Console.WriteLine(string.Format("{0}{1}", Jmeno.PadRight(padding), Penize));
Jmeno = "anotherPlayer";
Penize = 47;
Console.WriteLine(string.Format("{0}{1}", Jmeno.PadRight(padding), Penize));

生产

bustercze      147
JohnyPrcina    158
anotherPlayer  47

您可以使用 advanced features of string.Format:

string.Format("{0,-13}{1}")

你可以通过写str.PadRight(10)

来做同样的事情

你可以这样格式化字符串,-16在这里定义了你想要在左边对齐的数量space,如果你想要右边那么你可以使用+将其设置为基于 Jmeno

的最大可能长度
public override string ToString()
    {
        return string.Format("{0,-16}{1}", Jmeno, Penize);
    }