深入浅出WPF之Binding--笔记(2015.03.04)

XML语言可以方便地表示树形数据结构。HierarchicalDataTemplate类表示一个 DataTemplate,它支持 HeaderedItemsControl,比如 TreeViewItemMenuItem

XAML:

        <Window.Resources>
        <XmlDataProvider x:Key="xdp" XPath="FileSystem/Folder">
            <x:XData>
                <FileSystem xmlns="">
                    <Folder Name="Books">
                        <Folder Name="Programming">
                            <Folder Name="Windows">
                                <Folder Name="WPF"/>
                                <Folder Name="MFC"/>
                                <Folder Name="Delphi"/>
                            </Folder>
                        </Folder>
                        <Folder Name="Tools">
                            <Folder Name="Development"/>
                            <Folder Name="Designment"/>
                            <Folder Name="Players"/>
                        </Folder>
                    </Folder>
                </FileSystem>
            </x:XData>
        </XmlDataProvider>
    </Window.Resources>
    <Grid Background="LightBlue">
        <TreeView ItemsSource="{Binding Source={StaticResource ResourceKey=xdp}}">
            <TreeView.ItemTemplate>
                <HierarchicalDataTemplate ItemsSource="{Binding XPath=Folder}">
                    <TextBlock Text="{Binding XPath=@Name}"/>
                </HierarchicalDataTemplate>
            </TreeView.ItemTemplate>
        </TreeView>
    </Grid>

       LINQ查询的结果是一个IEnumerable<T>类型的对象,而IEnumerable<T>又派生自IEnumerable,所以它可以作为列表控件的ItemSource来使用。

XAML:

        <StackPanel Background="LightBlue">
        <ListView x:Name="listViewStudents" Height="143" Margin="5">
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="Id" Width="60" DisplayMemberBinding="{Binding Id}"/>
                    <GridViewColumn Header="Name" Width="100" DisplayMemberBinding="{Binding Name}"/>
                    <GridViewColumn Header="Age" Width="80" DisplayMemberBinding="{Binding Age}"/>
                </GridView>
            </ListView.View>
        </ListView>
        <Button Content="Load" Height="25" Margin="5" Click="Button_Click"/>
    </StackPanel>

C#代码:

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            List<Student> stuList = new List<Student>
            {
                new Student {Id = 1, Name = "Tim", Age = 20},
                new Student {Id = 2, Name = "Tom", Age = 21},
                new Student {Id = 3, Name = "Bruce", Age = 22},
                new Student {Id = 4, Name = "Tina", Age = 23},
                new Student {Id = 5, Name = "Mess", Age = 24},
                new Student {Id = 6, Name = "Howard", Age = 25}
            };

            this.listViewStudents.ItemsSource = from stu in stuList where stu.Name.StartsWith("T") select stu;
        }


你可能感兴趣的:(WPF,binding)