将上篇的this.listBoxStudents.DisplayMemberPath = "Name";注释。然后XAML代码改为:
<StackPanel x:Name="stackPanel" Background="LightBlue">
<TextBlock Text="Student ID:" FontWeight="Bold" Margin="5"/>
<TextBox x:Name="textBoxId" Margin="5"/>
<TextBlock Text="Student List:" FontWeight="Bold" Margin="5"/>
<ListBox x:Name="listBoxStudents" Height="110" Margin="5">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Id}" Width="30"/>
<TextBlock Text="{Binding Name}" Width="60"/>
<TextBlock Text="{Binding Age}" Width="30"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
在集合类型作为列表控件的ItemSource时,一般会考虑使用ObservableCollection<T>代替List<T>,因为ObservableCollection<T>类实现了INotifyCollectionChanged和INotifyPropertyChanged接口,能把集合的变化立刻通知显示它的列表控件,改变会立即显现出来。
当使用XML数据作为Binding的Source时,使用XPath而不是Path属性来指定数据的来源。
XML:
<?xml version="1.0" encoding="utf-8"?>
<StudentList>
<Student Id = "1">
<Name>Tim</Name>
</Student>
<Student Id = "2">
<Name>Tom</Name>
</Student>
<Student Id = "3">
<Name>Vena</Name>
</Student>
<Student Id = "4">
<Name>Emily</Name>
</Student>
</StudentList>
XAML:
<StackPanel Background="LightBlue">
<ListView x:Name="listViewStudent" Height="130" Margin="5">
<ListView.View>
<GridView>
<GridViewColumn Header="Id" Width="80" DisplayMemberBinding="{Binding [email protected]}"/>
<GridViewColumn Header="Name" Width="120" DisplayMemberBinding="{Binding XPath=Name}"/>
</GridView>
</ListView.View>
</ListView>
<Button Content="Load" Click="Button_Click" Height="25" Margin="5"/>
</StackPanel>
C#代码:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
XmlDocument doc = new XmlDocument();
doc.Load("RawData.xml");
XmlDataProvider xdp = new XmlDataProvider();
xdp.Document = doc;
xdp.XPath = @"/StudentList/Student";
this.listViewStudent.DataContext = xdp;
this.listViewStudent.SetBinding(ListView.ItemsSourceProperty, new Binding());
}
}