WPF应用Binding之ItemsSource

时间:2022-10-09 17:02:19


一、ListBox显示简单的列表信息(未使用DataTemplate)

(1) Student类

    public class Student
{
public string Name { get; set; }
public int Age { get; set; }
public int Id { get; set; }
}

 (2) xaml

    <Grid>
<StackPanel>
<TextBlock Text="SelectID:" Background="Aquamarine"/>
<TextBox x:Name="txtbox_SelectId"/>
<TextBlock Text="Students:" Background="Aquamarine"/>
<ListBox x:Name="listbox_Students"/>
</StackPanel>
</Grid>

(3) C#代码逻辑

    private void ShowStudent()
{
List<Student> studentList = new List<Student>()
{
new Student(){Id = 2003, Name = "tim", Age = 20},
new Student(){Id = 2004, Name = "tom", Age = 21},
new Student(){Id = 2005, Name = "toni", Age = 21},
new Student(){Id = 2006, Name = "fidy", Age = 23},
new Student(){Id = 2007, Name = "andy", Age = 22},
};

//ListBox数据绑定
listbox_Students.ItemsSource = studentList;//数据源
listbox_Students.DisplayMemberPath = "Name";//ListBox只显示Student的Name属性

//绑定被选中的id(2种方式均可)
#if true//方式1
Binding binding = new Binding("SelectedItem.Id") { Source = listbox_Students };
#else//方式2
Binding binding = new Binding();
binding.Path = new PropertyPath("SelectedItem.Id");
binding.Source = listbox_Students;
#endif
txtbox_SelectId.SetBinding(TextBox.TextProperty, binding);
}

二、ListBox显示Student信息(使用DataTemplate)

(1) Student类

    同上

(2) xaml

    <StackPanel>
<TextBlock Text="SelectID:" Background="Aquamarine"/>
<TextBox x:Name="txtbox_SelectId"/>
<TextBlock Text="Students:" Background="Aquamarine"/>
<ListBox x:Name="listbox_Students">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Path=Id}" Width="40"/>
<TextBlock Text="{Binding Path=Name}" Width="60"/>
<TextBlock Text="{Binding Path=Age}" Width="40"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>

(3) C#代码逻辑

        private void ShowStudent()
{
List<Student> studentList = new List<Student>()
{
new Student(){Id = 2003, Name = "tim", Age = 20},
new Student(){Id = 2004, Name = "tom", Age = 21},
new Student(){Id = 2005, Name = "toni", Age = 21},
new Student(){Id = 2006, Name = "fidy", Age = 23},
new Student(){Id = 2007, Name = "andy", Age = 22},
};

listbox_Students.ItemsSource = studentList;//数据源

//绑定被选中的id(2种方式均可)
#if true//方式1
Binding binding = new Binding("SelectedItem.Id") { Source = listbox_Students };
#else//方式2
Binding binding = new Binding();
binding.Path = new PropertyPath("SelectedItem.Id");
binding.Source = listbox_Students;
#endif
txtbox_SelectId.SetBinding(TextBox.TextProperty, binding);