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>