Bartosz Cieszewski
Bartosz Cieszewski

Reputation: 373

New line in ListBox with bound data

I'm putting data to ListBox from a list of objects using this simple code:

<ListBox Name="lbxListaZadan">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel xml:space="preserve" Orientation="Horizontal">
                <TextBlock Text="{Binding title}" />
                <TextBlock Text="&#10;" />
                <TextBlock Text="Priorytet: " />
                <TextBlock Text="{Binding priority}" />
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Instead of expected output:

Task1
Priorytet: 1
Task2
Priorytet:2
Task3
Priorytet: 3

I'm getting:

Task1Priorytet: 1

Task2Priorytet: 2

Task3Priorytet: 3

Why is the newline in a place I would not expect it to be, and how the hell can I reach the expected output in listbox.

Upvotes: 0

Views: 662

Answers (3)

Henk Holterman
Henk Holterman

Reputation: 273179

<DataTemplate>
    <StackPanel Orientation="Vertical">
      <TextBlock Text="{Binding title}" />
      <StackPanel Orientation="Horizontal">                         
         <TextBlock Text="Priorytet: " />
         <TextBlock Text="{Binding priority}" />
      </StackPanel>
    </StackPanel>
</DataTemplate>

A newline character can only work inside a single TextBlock, not between two of them.

Upvotes: 2

Stefan Over
Stefan Over

Reputation: 6046

The Environment.NewLine would only have the expected effect, if the texts are in the same TextBlock.
WPF then renders the Text property of the TextBlock with the new line in mind, which causes a line break.

To achieve the wanted behavior, you'd have add a vertical layout element:

<ListBox Name="lbxListaZadan">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel xml:space="preserve" Orientation="Vertical">
                <TextBlock Text="{Binding title}" />
                <StackPanel Orientation="horizontal">
                    <TextBlock Text="Priorytet: " />
                    <TextBlock Text="{Binding priority}" />
                </StackPanel>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Upvotes: 2

dkozl
dkozl

Reputation: 33364

You can put 2 TextBlocks in vertical StackPanel

<StackPanel>
    <TextBlock Text="{Binding title}" />
    <TextBlock Text="{Binding priority, StringFormat='Priorytet: {0}'}"  />
</StackPanel>

also instead of 2 TextBlocks for priority you can use one with StringFormat

Upvotes: 2

Related Questions