六、排序

如果想以特定的方式对数据进行排序,可以绑定到 CollectionViewSource,而不是直接绑定到 ObjectDataProvider。CollectionViewSource 则会成为数据源,并充当截取 ObjectDataProvider 中的数据的媒介,并提供排序、分组和筛选功能,然后将它传送到目标。

这个显示是使用 CollectionViewSource做为排序的数据源,首先将CollectionViewSource的Source 属性设置为 ObjectDataProvider的资源名称。然后通过设置CollectionViewSource.SortDescriptions属性,指定排序字段和排序顺序:

  1. <CollectionViewSource x:Key="studentsView" Source="{Binding Source={StaticResource students}}">
  2.  
  3. <CollectionViewSource.SortDescriptions>
  4.  
  5. <scm:SortDescription PropertyName="Name" Direction="Ascending" />
  6.  
  7. <scm:SortDescription PropertyName="Age" Direction="Descending" />
  8.  
  9. </CollectionViewSource.SortDescriptions>
  10.  
  11. </CollectionViewSource>

WPF中的DataContext属性是非常有用的,如果你有多个控件需要绑定同一个数据源,那么按照WinForm中的做法是给每个控件都绑定一次数据源,那么做重复代码就会很多。而在WPF中你可以首先把这些需要绑定同一个数据源的控件放在同一个容器控件内,然后将容器控件的 DataContext 设置为绑定源,容器内的控件的数据源绑定就可以不必再绑定,使用容器的数据源。例如,下面

的示例:StackPanel的 DataContext 属性绑定了数据源,DataGrid就可以不必再次绑定了,直接使用StackPanel绑定的数据源。

  1. <StackPanel DataContext="{StaticResource studentsView}">
  2.  
  3. <TextBlock Width="248" Height="24" Text="数据排序:"
  4.  
  5. TextWrapping="Wrap"/>
  6.  
  7. <DataGrid AutoGenerateColumns="False"
  8.  
  9. ItemsSource="{Binding}" CanUserAddRows="False">
  10.  
  11. <DataGrid.Columns>
  12.  
  13. <DataGridTextColumn Binding="{Binding Name}" Header="名称" />
  14.  
  15. <DataGridTextColumn Binding="{Binding Age}" Header="年龄" />
  16.  
  17. <DataGridTextColumn Binding="{Binding Country}" Header="国家" />
  18.  
  19. <DataGridTextColumn Binding="{Binding Birthday}" Header="出生日期" />
  20.  
  21. </DataGrid.Columns>
  22.  
  23. </DataGrid>
  24.  
  25. </StackPanel>

如果该容器没有定义 DataContext,那么它会继续查找下一个外部嵌套容器,直到它找到当前的 DataContext 为止。如下图所示。当点击列头时,数据就会进行顺序或逆序排序。如下图。

整个示例的全部代码如下:

  1. <Window x:Class="WpfApp1.WindowBindData"
  2.  
  3. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  4.  
  5. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  6.  
  7. xmlns:local="clr-namespace:WpfApp1.Services"
  8.  
  9. xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase"
  10.  
  11. Title="WindowBindData" Height="700" Width="500">
  12.  
  13. <Grid>
  14.  
  15. <Grid.RowDefinitions>
  16.  
  17. <RowDefinition Height="140"/>
  18.  
  19. <RowDefinition Height="150"/>
  20.  
  21. <RowDefinition Height="140"/>
  22.  
  23. <RowDefinition Height="100*"/>
  24.  
  25. </Grid.RowDefinitions>
  26.  
  27. <StackPanel Grid.Row="0">
  28.  
  29. <TextBlock Width="248" Height="24" Text="股票名称:"
  30.  
  31. TextWrapping="Wrap"/>
  32.  
  33. <ListBox x:Name="listStockName" Width="248" Height="56">
  34.  
  35. <ListBoxItem Content="全通教育"/>
  36.  
  37. <ListBoxItem Content="大智慧"/>
  38.  
  39. <ListBoxItem Content="宝钢股份"/>
  40.  
  41. <ListBoxItem Content="浦发银行"/>
  42.  
  43. <ListBoxItem Content="工商银行"/>
  44.  
  45. <ListBoxItem Content="中国建筑"/>
  46.  
  47. <ListBoxItem Content="中国南车"/>
  48.  
  49. </ListBox>
  50.  
  51. <TextBlock Width="248" Height="24" Text="你所选中的股票名称:" />
  52.  
  53. <TextBlock Width="248" Height="24" Text="{Binding ElementName=listStockName, Path=SelectedItem.Content}">
  54.  
  55. </TextBlock>
  56.  
  57. </StackPanel>
  58.  
  59. <StackPanel Grid.Row="1">
  60.  
  61. <TextBlock Width="248" Height="24" Text="颜色:"
  62.  
  63. TextWrapping="Wrap"/>
  64.  
  65. <ListBox x:Name="listColor" Width="248" Height="56">
  66.  
  67. <ListBoxItem Content="Blue"/>
  68.  
  69. <ListBoxItem Content="Red"/>
  70.  
  71. <ListBoxItem Content="Green"/>
  72.  
  73. <ListBoxItem Content="Gray"/>
  74.  
  75. <ListBoxItem Content="Cyan"/>
  76.  
  77. <ListBoxItem Content="GreenYellow"/>
  78.  
  79. <ListBoxItem Content="Orange"/>
  80.  
  81. </ListBox>
  82.  
  83. <TextBlock Width="248" Height="24" Text="改变背景色:" />
  84.  
  85. <TextBlock Width="248" Height="24" Text="{Binding ElementName=listColor, Path=SelectedItem.Content, Mode=OneWay}"
  86.  
  87. Background="{Binding ElementName=listColor, Path=SelectedItem.Content, Mode=OneWay}">
  88.  
  89. </TextBlock>
  90.  
  91. <TextBox Name="txtTwoWay" Text="{Binding ElementName=listColor,Path=SelectedItem.Content,Mode=TwoWay}"
  92.  
  93. Background="{Binding ElementName=listColor,Path=SelectedItem.Content,Mode=TwoWay}"></TextBox>
  94.  
  95. </StackPanel>
  96.  
  97. <StackPanel Grid.Row="2">
  98.  
  99. <StackPanel.Resources>
  100.  
  101. <XmlDataProvider x:Key="MyColors" Source="Colors.xml" XPath="colors">
  102.  
  103. </XmlDataProvider>
  104.  
  105. </StackPanel.Resources>
  106.  
  107. <TextBlock Width="248" Height="24" Text="XML数据绑定:"
  108.  
  109. TextWrapping="Wrap"/>
  110.  
  111. <ListBox x:Name="listXmlColor" Width="248" Height="56" IsSynchronizedWithCurrentItem="True"
  112.  
  113. ItemsSource="{Binding Source={StaticResource MyColors},XPath=color/@name}">
  114.  
  115. </ListBox>
  116.  
  117. <TextBlock Width="248" Height="24" Text="选中的颜色:" />
  118.  
  119. <TextBlock Width="248" Height="24" Text="{Binding ElementName=listXmlColor, Path=SelectedValue, Mode=OneWay}"
  120.  
  121. >
  122.  
  123. </TextBlock>
  124.  
  125. </StackPanel>
  126.  
  127. <StackPanel Grid.Row="3">
  128.  
  129. <StackPanel.Resources>
  130.  
  131. <ObjectDataProvider x:Key="students" ObjectType="{x:Type local:StudentService}" MethodName="GetStudentList">
  132.  
  133. </ObjectDataProvider>
  134.  
  135. <DataTemplate x:Key="studentLayout" DataType="students">
  136.  
  137. <StackPanel Orientation="Horizontal">
  138.  
  139. <TextBlock Text="{Binding Path=Name}"
  140.  
  141. FontWeight="Bold" Foreground="Blue"/>
  142.  
  143. <TextBlock Text=", "></TextBlock>
  144.  
  145. <TextBlock Text="{Binding Path=Age}"></TextBlock>
  146.  
  147. <TextBlock Text=", "></TextBlock>
  148.  
  149. <TextBlock Text="{Binding Path=Birthday}"></TextBlock>
  150.  
  151. <TextBlock Text=", "></TextBlock>
  152.  
  153. <TextBlock Text="{Binding Path=Country}"></TextBlock>
  154.  
  155. </StackPanel>
  156.  
  157. </DataTemplate>
  158.  
  159. <CollectionViewSource x:Key="studentsView" Source="{Binding Source={StaticResource students}}">
  160.  
  161. <CollectionViewSource.SortDescriptions>
  162.  
  163. <scm:SortDescription PropertyName="Name" Direction="Ascending" />
  164.  
  165. <scm:SortDescription PropertyName="Age" Direction="Descending" />
  166.  
  167. </CollectionViewSource.SortDescriptions>
  168.  
  169. </CollectionViewSource>
  170.  
  171. </StackPanel.Resources>
  172.  
  173. <TextBlock Width="248" Height="24" Text="对象数据绑定:"
  174.  
  175. TextWrapping="Wrap"/>
  176.  
  177. <ListBox x:Name="listObjectBind" Width="450" Height="80" IsSynchronizedWithCurrentItem="True"
  178.  
  179. ItemsSource="{Binding Source={StaticResource students}}"
  180.  
  181. ItemTemplate="{DynamicResource studentLayout}">
  182.  
  183. </ListBox>
  184.  
  185. <TextBlock Width="248" Height="24" Text="数据排序:"
  186.  
  187. TextWrapping="Wrap"/>
  188.  
  189. <DataGrid DataContext="{StaticResource studentsView}" AutoGenerateColumns="False"
  190.  
  191. ItemsSource="{Binding}" CanUserAddRows="False">
  192.  
  193. <DataGrid.Columns>
  194.  
  195. <DataGridTextColumn Binding="{Binding Name}" Header="名称" />
  196.  
  197. <DataGridTextColumn Binding="{Binding Age}" Header="年龄" />
  198.  
  199. <DataGridTextColumn Binding="{Binding Country}" Header="国家" />
  200.  
  201. <DataGridTextColumn Binding="{Binding Birthday}" Header="出生日期" />
  202.  
  203. </DataGrid.Columns>
  204.  
  205. </DataGrid>
  206.  
  207. </StackPanel>
  208.  
  209. </Grid>
  210.  
  211. </Window>
  1. using System;
  2.  
  3. using System.Collections.Generic;
  4.  
  5. using System.Linq;
  6.  
  7. using System.Text;
  8.  
  9. using System.Threading.Tasks;
  10.  
  11. using System.Windows;
  12.  
  13. namespace WpfApp1.Models
  14.  
  15. {
  16.  
  17. public class Student : DependencyObject
  18.  
  19. {
  20.  
  21. //声明一个静态只读的DependencyProperty字段
  22.  
  23. public static readonly DependencyProperty NameProperty;
  24.  
  25. public static readonly DependencyProperty AgeProperty;
  26.  
  27. public static readonly DependencyProperty BirthdayProperty;
  28.  
  29. public static readonly DependencyProperty CountryProperty;
  30.  
  31. static Student()
  32.  
  33. {
  34.  
  35. //注册我们定义的依赖属性Name,Age,birthday,Country
  36.  
  37. NameProperty = DependencyProperty.Register("Name", typeof(string), typeof(Student),
  38.  
  39. new PropertyMetadata("名称", OnValueChanged));
  40.  
  41. AgeProperty = DependencyProperty.Register("Age", typeof(string), typeof(Student),
  42.  
  43. new PropertyMetadata("年龄", OnValueChanged));
  44.  
  45. BirthdayProperty = DependencyProperty.Register("Birthday", typeof(string), typeof(Student),
  46.  
  47. new PropertyMetadata("出生日期", OnValueChanged));
  48.  
  49. CountryProperty = DependencyProperty.Register("Country", typeof(string), typeof(Student),
  50.  
  51. new PropertyMetadata("国家", OnValueChanged));
  52.  
  53. }
  54.  
  55. private static void OnValueChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
  56.  
  57. {
  58.  
  59. //当值改变时,我们可以在此做一些逻辑处理
  60.  
  61. }
  62.  
  63. //属性包装器,通过它来读取和设置我们刚才注册的依赖属性
  64.  
  65. public string Name
  66.  
  67. {
  68.  
  69. get { return (string)GetValue(NameProperty); }
  70.  
  71. set { SetValue(NameProperty, value); }
  72.  
  73. }
  74.  
  75. public string Age
  76.  
  77. {
  78.  
  79. get { return (string)GetValue(AgeProperty); }
  80.  
  81. set { SetValue(AgeProperty, value); }
  82.  
  83. }
  84.  
  85. public string Birthday
  86.  
  87. {
  88.  
  89. get { return (string)GetValue(BirthdayProperty); }
  90.  
  91. set { SetValue(BirthdayProperty, value); }
  92.  
  93. }
  94.  
  95. public string Country
  96.  
  97. {
  98.  
  99. get { return (string)GetValue(CountryProperty); }
  100.  
  101. set { SetValue(CountryProperty, value); }
  102.  
  103. }
  104.  
  105. }
  106.  
  107. }
  1. using System;
  2.  
  3. using System.Collections.Generic;
  4.  
  5. using System.Linq;
  6.  
  7. using System.Text;
  8.  
  9. using System.Threading.Tasks;
  10.  
  11. using WpfApp1.Models;
  12.  
  13. namespace WpfApp1.Services
  14.  
  15. {
  16.  
  17. public class StudentService
  18.  
  19. {
  20.  
  21. public List<Student> GetStudentList()
  22.  
  23. {
  24.  
  25. Student liang = new Student();
  26.  
  27. liang.Age = "";
  28.  
  29. liang.Name = "梁丘";
  30.  
  31. liang.Birthday = "1990-02-03";
  32.  
  33. liang.Country = "中国";
  34.  
  35. Student zuo = new Student();
  36.  
  37. zuo.Age = "";
  38.  
  39. zuo.Name = "左丘";
  40.  
  41. zuo.Birthday = "1992-02-03";
  42.  
  43. zuo.Country = "中国";
  44.  
  45. Student diwu = new Student();
  46.  
  47. diwu.Age = "";
  48.  
  49. diwu.Name = "第五言";
  50.  
  51. diwu.Birthday = "1982-11-03";
  52.  
  53. diwu.Country = "中国";
  54.  
  55. Student yang = new Student();
  56.  
  57. yang.Age = "";
  58.  
  59. yang.Name = "羊舌微";
  60.  
  61. yang.Birthday = "2002-11-13";
  62.  
  63. yang.Country = "中国";
  64.  
  65. List<Student> personList = new List<Student>();
  66.  
  67. personList.Add(liang);
  68.  
  69. personList.Add(zuo);
  70.  
  71. personList.Add(diwu);
  72.  
  73. personList.Add(yang);
  74.  
  75. return personList;
  76.  
  77. }
  78.  
  79. }
  80.  
  81. }

WPF入门教程系列十八——WPF中的数据绑定(四)的更多相关文章

  1. WPF入门教程系列十五——WPF中的数据绑定(一)

    使用Windows Presentation Foundation (WPF) 可以很方便的设计出强大的用户界面,同时 WPF提供了数据绑定功能.WPF的数据绑定跟Winform与ASP.NET中的数 ...

  2. WPF入门教程系列十六——WPF中的数据绑定(二)

    三.绑定模式 通过上一文章中的示例,学习了简单的绑定方式.在这里的示例,要学习一下绑定的模式,和模式的使用效果. 首先,我们来做一个简单示例,这个示例是根据ListBox中的选中项,去改变TextBl ...

  3. WPF入门教程系列十九——ListView示例(一)

    经过前面的学习,今天我做一个比较综合的WPF程序示例,主要包括以下功能: 1) 查询功能.从数据库(本地数据库(local)/Test中的S_City表中读取城市信息数据,然后展示到WPF的Windo ...

  4. WPF入门教程系列十四——依赖属性(四)

    六.依赖属性回调.验证及强制值 我们通过下面的这幅图,简单介绍一下WPF属性系统对依赖属性操作的基本步骤: 借用一个常见的图例,介绍一下WPF属性系统对依赖属性操作的基本步骤: 第一步,确定Base ...

  5. WPF入门教程系列十二——依赖属性(二)

    二. 依赖属性的优先级 由于WPF 允许我们可以在多个地方设置依赖属性的值,所以我们就必须要用一个标准来保证值的优先级别.比如下面的例子中,我们在三个地方设置了按钮的背景颜色,那么哪一个设置才会是最终 ...

  6. WPF入门教程系列十——布局之Border与ViewBox(五)

    九. Border Border 是一个装饰的控件,此控件绘制边框及背景,在 Border 中只能有一个子控件,若要显示多个子控件,需要将一个附加的 Panel 控件放置在父 Border 中.然后可 ...

  7. WPF入门教程系列二十三——DataGrid示例(三)

    DataGrid的选择模式 默认情况下,DataGrid 的选择模式为“全行选择”,并且可以同时选择多行(如下图所示),我们可以通过SelectionMode 和SelectionUnit 属性来修改 ...

  8. WPF入门教程系列三——Application介绍(续)

    接上文WPF入门教程系列二——Application介绍,我们继续来学习Application 三.WPF应用程序的关闭 WPF应用程序的关闭只有在应用程序的 Shutdown 方法被调用时,应用程序 ...

  9. WPF入门教程系列二——Application介绍

    一.Application介绍 WPF和WinForm 很相似, WPF与WinForm一样有一个 Application对象来进行一些全局的行为和操作,并且每个 Domain (应用程序域)中仅且只 ...

随机推荐

  1. AutoCAD .net 开发 SelectionFilter Foreach Linq 性能比较

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...

  2. Set和存储顺序

    set(interface) 存入Set的每个元素必须是唯一的,因为Set不保存重复的元素.加入Set的元素必须定义 equal()方法以确保对象的唯一性.Set和Collection有完全一样的接口 ...

  3. tomcat在linux下自启动

    Linux下设置tomcat开机自启动  一.以root用户登录系统: 二.进入init.d文件夹 cd /etc/init.d/ 三.创建并打开tomcat文件 vi tomcat 四.tomcat ...

  4. Ambari组件黄色预警

    Ambari组件黄色预警 组件上为黄色问号,代表心跳丢失,解决如下: 1.  查看个节点之间是否可以相互通信,若ssh连接不上,有可能是该节点关机了,没有打开,手动开启该节点,再次验证是否可互通. 2 ...

  5. tcpdum使用

    安装tcpdump包:yum install -y tcpdump ,不加”-i eth0”是表示抓取所有的接口包括lo. 1.抓取包含10.88.88.96的数据包 # tcpdump -i eth ...

  6. JS中数组的操作[转]

    1.数组的创建 var arrayObj = new Array(); //创建一个数组 var arrayObj = new Array([size]); //创建一个数组并指定长度,注意不是上限, ...

  7. 【Beta】Daily Scrum Meeting第七次

    1.任务进度 学号 已完成 接下去要做 502 发布任务到服务器 测试 509 将各api的处理逻辑放到类里面 让主api调用这些类 517 删除任务和教师的控件及逻辑 提交报课审核信息 530 完善 ...

  8. 汉字正则表达式[\u4E00-\u9FFF]原因

    转载易天:正则表达式的汉字匹配 这里是几个主要非英文语系字符范围 2E80-33FFh:中日韩符号区.收容康熙字典部首.中日韩辅助部首.注音符号.日本假名.韩文音符,中日韩的符号.标点.带圈或带括符文 ...

  9. webform 组合查询

    界面: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx ...

  10. Xcode 升级后,常常遇到的遇到的警告、错误,解决方法(转)

    从sdk3.2.5升级到sdk 7.1中间废弃了很多的方法,还有一些逻辑关系更加严谨了.1,警告:“xoxoxoxo”  is deprecated解决办法:查看xoxoxoxo的这个方法的文档,替换 ...