一般最簡單的ItemsControl的寫法是
<ItemsControl ItemsSource="{Binding Students}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
後臺寫
public class ListDemoViewModel:BindableBase
{
private ObservableCollection<Student> _students;
public ObservableCollection<Student> Students
{
get => _students;
set => SetProperty(ref _students, value);
}
public ListDemoViewModel()
{
Students = new ObservableCollection<Student>() { new Student() { Name = "123" } };
}
但是以後資料模板和控制元件模板都會變得很複雜,如果我們把繫結同時寫在一個xaml,那麼這個xaml會顯得異常臃腫。
1、先說資料的繫結,我們把上面的Name提取出去,放在一個新建的UserControl
可以寫
<TextBlock Text="{Binding Students[0].Name}">
<TextBlock.DataContext>
<viewModel:ListDemoViewModel/>
</TextBlock.DataContext>
</TextBlock>
主介面改為
<ItemsControl ItemsSource="{Binding Students}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<local:GroupBoxView/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>