6

I'm binding the columnheaders of a datagrid to an observablecollection of dates, to display the day and date in the columnheader. This works fine. However, I would like to add a newline or break using the string. How can this be done?

<DataGridTextColumn>
    <DataGridTextColumn.HeaderTemplate>
        <DataTemplate>
            <TextBlock TextWrapping="Wrap" Text="{Binding DataContext.Week.Days[1].Date, StringFormat=ddd dd.MM.yyyy, RelativeSource={RelativeSource AncestorType=DataGrid}}"/>

This displays the following Text: Tue 06.12.2016 What I want it to display is

Tue
06.12.2016

Petter Hesselberg
  • 5,062
  • 2
  • 24
  • 42
Mister 832
  • 1,177
  • 1
  • 15
  • 34

3 Answers3

15

For folks looking to put a newline in StringFormat (or ContentStringFormat, if you need to use Label), this answer has a way. You can use:

HEX represenation of CR/LF &#x0d;&#x0a; (or just line feed &#x0a;):

So, for the code in question:

StringFormat=ddd&#x0d;&#x0a;dd.MM.yyyy
Vimes
  • 10,577
  • 17
  • 66
  • 86
8

Set the TextBlock's Inlines property:

<TextBlock DataContext="{Binding DataContext.Week.Days[1].Date,
                         RelativeSource={RelativeSource AncestorType=DataGrid}}">
    <Run Text="{Binding Mode=OneWay, StringFormat=ddd}"/>
    <LineBreak/>
    <Run Text="{Binding Mode=OneWay, StringFormat=dd.MM.yyyy}"/>
</TextBlock>
Clemens
  • 123,504
  • 12
  • 155
  • 268
2

StringFormat isn't always an intuitive syntax, but I prefer Vimes solution in combination with TargetNullValue over the accepted solution.

It means I can only add a line-break if the second run has a value

<TextBlock>
  <Run Text="{Binding Message, Mode=OneTime}" />
  <Run Text="{Binding Exception, Mode=OneTime, TargetNullValue='', StringFormat={}&#x0d;&#x0a;{0}}"  />
</TextBlock>