1、WPF MarkupExtension的學習
public class StudentList: ObservableCollection<Student>
{
public StudentList()
{
Add(new Student() { Id=1,Name="張三"});
Add(new Student() { Id = 2, Name = "李四" });
}
}
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
}
public class StudentProviderExtension : MarkupExtension
{
private Type bindType;
public Type BindType
{
get=>bindType;
set => bindType = value;
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
Type type=Nullable.GetUnderlyingType(bindType)??bindType;
return Activator.CreateInstance(type);
}
}
XAML程式碼
<Window.Resources>
<markup:StudentProvider x:Key="students" BindType="{x:Type markup:StudentList}"/>
</Window.Resources>
<Grid>
<ItemsControl ItemsSource="{Binding Source={StaticResource students}}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Id}" />
<TextBlock Text="{Binding Name}" />
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>