Search code examples
wpfstringformattextblocklistboxitem

How to format text in a ListBox where items are added dynamically?


I need to format the text in each textblock, which is an item of my ListBox. I have managed to make something but it doesnt look the same as if I would call the Console.WriteLine-Method.

private void addNewGameItem(string gamename, string lastChangedDate)
    {
        ListBoxItem lbi = new ListBoxItem();
        StackPanel stpl = new StackPanel();
        TextBlock tbl = new TextBlock();

        tbl.Text = String.Format("{0,-100} {1,30}", gamename, lastChangedDate);
        tbl.FontSize = textBlockFontsize;

        stpl.Orientation = Orientation.Horizontal;
        stpl.Children.Add(tbl);
        lbi.Content = stpl;
        savedGamesList.Items.Add(lbi);//Add the ListBoxItem to the ListBox
    }

The problem is that if the gamename is longer than for example the previous one, the date will appear futher right. How can I format this, that it doesnt matter how long the gamename is, so the date-string will start on the same position, in each textblock?


Solution

  • This might be easier done in XAML rather than the code behind as you can more easily define the DataTemplate to be used to display your list items that way. Make your list of games an ObservableCollection and bind the ItemsSource of your list box to that. This will mean it auto-updates when you add a new item to the list.

    Then you can split the string into two parts, one for the game name the other for the date:

    <ListBoxItem ...>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding GameName}"/>
                <TextBlock Text="{Binding LastChangedDate}"
                           HorizontalAlignment="Right"/>
            </StackPanel>
        </DataTemplate>
    </ListBoxItem>
    

    Then in the ListBox style definition include the line:

    HorizontalContentAlignment="Stretch"
    

    This will make each list box item fill the entire width of the list box and (as long as the dates are formatted so that they all come out the same length) align them correctly.