mmvsbg
mmvsbg

Reputation: 3588

C# string padding in WPF

I'm writing a WPF application on C# which has a ListBox in it. The list box has an item on each row in the following format:

ID Name     Price

I know that the ID has the maximum of 3 numbers, the minimum of one and the name is less than 25 characters so I want to align those 3 values in columns, something like this:

194 Item Name 1          24.99
1   Item Other Name       4.00
13  Item Item Item       32.22

And so on... I'm tried couple of things:

string.Format("{0} {1} {2:0.00}", id.ToString().PadRight(4), name.PadRight(25), price)

The other option I tried:

string.Format("{0, -4} {1, -25} {2:0.00}", id, name, price)

Unfortunately every time I get an ID of 3 numbers it pushes the text a little bit further to the right so the columns are not aligned. Any tips or ideas how to fix that?

Upvotes: 0

Views: 433

Answers (1)

OneFineDay
OneFineDay

Reputation: 9024

With WPF you have the option to have multiple Textblocks in a StackPanel that is inside of the DataTemplate of the Listbox's ItemTemplate. @Clemens has a great link for this. You can also set the StackPanels Orientation to Horizontal so all are on one line. This way you can set the TextAlignment to Right or Left. If the StackPanel does not work well you can also use a Grid and set GridColumns and place the Textblocks to a specific Column.

Upvotes: 2

Related Questions