我的思想天马行空1

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>
posted @ 2024-12-09 00:49  孤沉  阅读(4)  评论(0编辑  收藏  举报