C# Format-在两列中设置两个变量的格式
我正在开发一个应用程序,我需要帮助。 在这个应用程序中,有一个列表框,其中将显示所有用户(类似于记分板)。在用户的方法ToString()中,我将string.Format设置为返回两个变量(Name和Money)。 但当我运行该应用程序时,我会得到如下输出:C# Format-在两列中设置两个变量的格式,c#,listbox,tostring,string.format,C#,Listbox,Tostring,String.format,我正在开发一个应用程序,我需要帮助。 在这个应用程序中,有一个列表框,其中将显示所有用户(类似于记分板)。在用户的方法ToString()中,我将string.Format设置为返回两个变量(Name和Money)。 但当我运行该应用程序时,我会得到如下输出: bustercze 147 JohnyPrcina 158 anotherPlayer 47 bustercze 147 JohnyPrcina 158 anotherPlayer 47 但我希望输出是
bustercze 147
JohnyPrcina 158
anotherPlayer 47
bustercze 147
JohnyPrcina 158
anotherPlayer 47
但我希望输出是这样的:
bustercze 147
JohnyPrcina 158
anotherPlayer 47
bustercze 147
JohnyPrcina 158
anotherPlayer 47
我希望你没弄错。你可以帮助我
My ToString()代码:
我已经尝试过的:
1.(没有帮助)
2.(也没有帮助)使用以下格式:“{0,-13}{1}”
注意:您可能希望将13更改为20或25,这取决于Jmeno
可以使用多长时间
编辑:如果要在列表框中显示,则需要使用单空格字体: 在以下
InitializeComponent()
或填充数据之前/之后添加此行:
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>
代码
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
您可以使用:
您可以通过编写
str.PadRight(10)
来完成同样的事情。您可以通过这种方式格式化字符串,-16
在这里定义您想要在左侧的对齐空间的数量,如果您想要在右侧对齐,那么您可以使用+
将其设置为基于Jmeno
的最大可能长度
public override string ToString()
{
return string.Format("{0,-16}{1}", Jmeno, Penize);
}
Xiaoy312也有一个很好的答案,尽管PadRight允许您指定填充字符。。。如果有价值的话。另外,您可以使用变量修改填充。我做错什么了吗D我的代码:public override string ToString(){return string.Format(“{0,-13}{1}”,Jmeno,Penize);}输出:是否在列表框、复选框、列表视图中显示它?这是因为没有单空格字体。(“1il”看起来比“MQ”短”)我正在列表框中显示它,那么我该如何修复它呢?@LukasSeidler更新了我的答案我现在看起来可能是个十足的傻瓜。但我得到的是:“列表框不包含字体的定义”和“FontFamily不包含GenericMonospace的定义”我不知道它是否会对你有所帮助,但我正在使用WPF no WinForm。我正在更正。请看这里并检查你的其他内容。我想这可能是Xiaoy312所说的:这是因为没有单空格字体。(“1il”看起来比“MQ”短)是否可以以某种方式修复此问题?也许通过改变字体?你使用的是WPF列表框吗?这可能是字体问题。但是如果是WPF listbox,最好是制作一个有两列的模板,而不是填充。这应该很有用-制作一个ItemTemplate-你的目标是什么:Winforms、WPF、ASP。。?始终正确标记您的问题!-Winforms:只有使用固定字体(如Courier或ConsoleAs)时,这种方式才有效。除此之外,请使用ListView!
public override string ToString()
{
return string.Format("{0,-16}{1}", Jmeno, Penize);
}