C# TextBlock显示对象列表

C# TextBlock显示对象列表,c#,wpf,xaml,C#,Wpf,Xaml,如果使用以下代码在列表框中显示对象,如何在文本块中显示它 listStudents.Items.Clear(); foreach (Student sRef in StudentList) { listStudents.Items.Add(sRef); } 如果您只想显示一个对象列表,而不需要选择和其他ListBox功能,则可以方便地使用ItemsControl-它具有itemstemplate属性来控制每个项和其他有用内容的外观(实际上,ListBox继承ItemsControl)。

如果使用以下代码在
列表框中显示对象
,如何在
文本块中显示它

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

如果您只想显示一个对象列表,而不需要选择和其他
ListBox
功能,则可以方便地使用
ItemsControl
-它具有
itemstemplate
属性来控制每个项和其他有用内容的外观(实际上,
ListBox
继承
ItemsControl
)。只需使用
itemsStudent
类型为
ItemsControl
的变量,并使用相同的代码:

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

如果要在单个
TextBlock
中显示多行学生,可以将以下内容附加到
TextBlock
Text
属性:

foreach (Student sRef in StudentList)
{
    textBlock1.Text += sRef.Firstname + " " sRef.Lastname + Environment.NewLine;
}
但是您可能需要定义一个
ItemTemplate
,它定义视图中每个
Student
对象的外观:

<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>

更改列表框上的数据模板
<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>