4. Binding to Collections
In actual development, we usually bind a collection data object (such as a data table) to a DataGrid or ListBox list control, and we need to use the collection binding method. WPF specifically implements a system.collections.objectmodel.observablecollection<t> generic collection that eliminates the time we have to write the collection code with the change notification feature.
Window1.xaml
<Window x:Class="Learn.WPF.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1">
<Grid>
<StackPanel>
<ListBox x:Name="listbox1"></ListBox>
</StackPanel>
</Grid>
</Window>
Window1.xaml.cs
public class Personal
{
public string Name { get; set; }
public int Age { get; set; }
public string Sex { get; set; }
}
public class PersonalList : ObservableCollection<Personal>
{
}
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
var list = new PersonalList
{
new Personal { Name = "Tom", Age = 10, Sex = "Male" },
new Personal { Name = "Mary", Age = 15, Sex = "Female" },
new Personal { Name = "Jack", Age = 12, Sex = "Male" },
};
var binding = new Binding{ Source = list };
this.listbox1.SetBinding(ListBox.ItemsSourceProperty, binding);
this.listbox1.DisplayMemberPath = "Name";
}
}
Note Use the DisplayMemberPath property to specify the contents of the ListBoxItem, otherwise call ToString () to display the result.
Of course, we can also directly bind the list data in the logical resource.
Window1.xaml
<Window x:Class="Learn.WPF.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:my="clr-namespace:Learn.WPF"
Title="Window1">
<Window.Resources>
<my:PersonalList x:Key="personals" >
<my:Personal Name="Tom" Age="10" Sex="Male" />
<my:Personal Name="Mary" Age="15" Sex="Female" />
<my:Personal Name="Jack" Age="12" Sex="Male" />
</my:PersonalList>
</Window.Resources>
<Grid>
<StackPanel>
<ListBox x:Name="listbox2"
ItemsSource="{Binding Source={StaticResource personals}}"
DisplayMemberPath="Name">
</ListBox>
</StackPanel>
</Grid>
</Window>