0

If I use following code to display objects in a ListBox, how can I display it in a TextBlock?

listStudents.Items.Clear();
foreach (Student sRef in StudentList)
{
    listStudents.Items.Add(sRef);
}
1
  • Change your data template on the ListBox Commented Aug 28, 2017 at 7:09

3 Answers 3

1

If you want to display several lines of students in a single TextBlock, you could append to the Text property of the TextBlock:

foreach (Student sRef in StudentList)
{
    textBlock1.Text += sRef.Firstname + " " sRef.Lastname + Environment.NewLine;
}

But you probably want to define an ItemTemplate that defines the appearance of each Student object in the view:

<ListBox x:Name="listStudents">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding Firstname}" />
                <TextBlock Text="{Binding Lastname}" Margin="2 0 0 0" />
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
Sign up to request clarification or add additional context in comments.

Comments

0
listStudent.Items.Clear();
        foreach (Student sRef in StudentList)
        {
            listSubjects.Items.Add(sRef.firstname + " " + sRef.lastname);
        }

Comments

0

If you want just to display a list of objects without selection and other ListBox functionality, it's convenient to use ItemsControl - it has ItemTemplate property to control an appearance of each item and other useful stuff (actually, ListBox inherits ItemsControl). Just use itemsStudent variable of type ItemsControl and use the same code:

itemsStudent.Items.Clear();
foreach (Student sRef in StudentList)
{
    itemsStudent.Items.Add(sRef);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.