WPF真入门教程20--数据排序
如果想以特定的方式对数据进行排序,可以绑定到 CollectionViewSource,而不是直接绑定到 ObjectDataProvider。CollectionViewSource 则会成为数据源,并充当截取 ObjectDataProvider 中的数据的媒介,并提供排序、分组和筛选功能,然后将它传送到目标。 这个示例是使用 CollectionViewSource做为排序的数据源,首先将CollectionViewSource的Source 属性设置为 ObjectDataProvider的资源名称。然后通过设置CollectionViewSource.SortDescriptions属性,指定排序字段和排序顺序,WPF中的DataContext属性是非常有用的,如果你有多个控件需要绑定同一个数据源,那么按照WinForm中的做法是给每个控件都绑定一次数据源,那么做重复代码就会很多。而在WPF中你可以首先把这些需要绑定同一个数据源的控件放在同一个容器控件内,然后将容器控件的 DataContext 设置为绑定源,容器内的控件的数据源绑定就可以不必再绑定,使用容器的数据源。
首先创建一个类Person,代码如下:
class Person : DependencyObject
{
//声明一个静态只读的DependencyProperty字段
public static readonly DependencyProperty NameProperty;
public static readonly DependencyProperty AgeProperty;
public static readonly DependencyProperty BirthdayProperty;
public static readonly DependencyProperty CountryProperty;
static Person()
{
//注册我们定义的依赖属性Name,Age,birthday,Country
NameProperty = DependencyProperty.Register("Name", typeof(string), typeof(Person),
new PropertyMetadata("名称", OnValueChanged));
AgeProperty = DependencyProperty.Register("Age", typeof(string), typeof(Person),
new PropertyMetadata("年龄", OnValueChanged));
BirthdayProperty = DependencyProperty.Register("Birthday", typeof(string), typeof(Person),
new PropertyMetadata("出生日期", OnValueChanged));
CountryProperty = DependencyProperty.Register("Country", typeof(string), typeof(Person),
new PropertyMetadata("国家", OnValueChanged));
}
private static void OnValueChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
//当值改变时,我们可以在此做一些逻辑处理
}
//属性包装器,通过它来读取和设置我们刚才注册的依赖属性
public string Name
{
get { return (string)GetValue(NameProperty); }
set { SetValue(NameProperty, value); }
}
public string Age
{
get { return (string)GetValue(AgeProperty); }
set { SetValue(AgeProperty, value); }
}
public string Birthday
{
get { return (string)GetValue(BirthdayProperty); }
set { SetValue(BirthdayProperty, value); }
}
public string Country
{
get { return (string)GetValue(CountryProperty); }
set { SetValue(CountryProperty, value); }
}
}
然后添加一个类PersonService,代码如下:
class PersonService
{
public List<Person> GetPersonList()
{
Person liang = new Person();
liang.Age = "18";
liang.Name = "梁二狼";
liang.Birthday = "1990-02-03";
liang.Country = "中国";
Person zuo = new Person();
zuo.Age = "22";
zuo.Name = "胡贵";
zuo.Birthday = "1992-02-03";
zuo.Country = "英国";
Person diwu = new Person();
diwu.Age = "32";
diwu.Name = "花三少";
diwu.Birthday = "1982-11-03";
diwu.Country = "中国";
Person yang = new Person();
yang.Age = "12";
yang.Name = "天雨星";
yang.Birthday = "2002-11-13";
yang.Country = "中国";
List<Person> personList = new List<Person>();
personList.Add(liang);
personList.Add(zuo);
personList.Add(diwu);
personList.Add(yang);
return personList;
}
}
然后在grid中添加布局控件,StackPanel,在StackPanel里添加表格控件DataGrid,xaml代码如下(接上一节代码):
<Window x:Class="WpfApp6.BindWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp6"
xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase"
mc:Ignorable="d"
Title="BindWindow" Height="765" Width="980">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="250"/>
<RowDefinition Height="200"/>
<RowDefinition Height="138*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<StackPanel Grid.Row="0" Grid.Column="0">
<TextBlock Width="248" Height="24" Text="简单绑定,股票名称:" TextWrapping="Wrap" FontSize="15"/>
<ListBox Name="mylista" Width="348" Height="150" FontSize="15" Margin="0,0">
<ListBoxItem Content="全通教育"/>
<ListBoxItem Content="京大智慧"/>
<ListBoxItem Content="宝钢股份"/>
<ListBoxItem Content="浦发银行"/>
<ListBoxItem Content="工商银行"/>
<ListBoxItem Content="中国建筑"/>
<ListBoxItem Content="长城汽车"/>
<ListBoxItem Content="山东电子"/>
<ListBoxItem Content="浙江吉利"/>
</ListBox>
<TextBlock Width="248" Height="24" Text="你选中的股票:" Margin="0,5,110,0" FontSize="15"/>
<!--ElementName 属性指示要绑定的控件名称。Path 属性指示绑定到ListBox元素的属性-->
<TextBlock Width="248" Height="24" Text="{Binding ElementName=mylista,Path=SelectedItem.Content}" FontSize="15" Margin="0,0,110,0"/>
</StackPanel>
<StackPanel Grid.Row="0" Grid.Column="1" HorizontalAlignment="Left" Height="240" Margin="10,10,0,0" VerticalAlignment="Top" Width="466">
<Label Content="绑定多个控件及单向双向绑定和更新触发器" FontSize="15" />
<ListBox Height="73" Margin="40,0,60,0" FontSize="15" Name="mylistb">
<ListBoxItem Content="green"/>
<ListBoxItem Content="blue"/>
<ListBoxItem Content="black"/>
<ListBoxItem Content="yellow"/>
<ListBoxItem Content="orange"/>
</ListBox>
<Label Content="背景色" Height="23" FontSize="12" Margin="0,2,366,0"/>
<!--TwoWay双向绑定,OneWay单向绑定-->
<!--UpdateSourceTrigger意指更新触发器,表示更新数据源方式:Explicit、LostFocus(默认) 和 PropertyChanged
1:Explicit,则不会更新源,除非从代码中调用 BindingExpression.UpdateSource
2:LostFocus ,默认值,指示该控件失去焦点时才会更新数据源。
3:PropertyChanged,控制属性每次发生更改时就立即更新数据源。-->
<TextBox FontSize="15" Text="{Binding ElementName=mylistb, Path=SelectedItem.Content, Mode=TwoWay,UpdateSourceTrigger=LostFocus}" Background="{Binding ElementName=mylistb, Path=SelectedItem.Content, Mode=OneWay}" Margin="0,0,306,0"/>
<TextBox FontSize="15" Text="{Binding ElementName=mylistb, Path=SelectedItem.Content, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" Margin="0,10,306,0"/>
<TextBlock TextWrapping="Wrap" Text="" Height="39" Margin="0,10,0,0" Background="{Binding ElementName=mylistb, Path=SelectedItem.Content, Mode=OneWay}"/>
</StackPanel>
<!--XML数据绑定-->
<StackPanel HorizontalAlignment="Left" Height="180" Margin="10,10,0,0" Grid.Row="1" Grid.Column="0" VerticalAlignment="Top" Width="476">
<!--Resources属性指定外部资源为XmlDataProvider-->
<StackPanel.Resources>
<!--Source 属性指定资源文件名,XPath 属性指定路径名-->
<XmlDataProvider x:Key="MyColors" Source="Colors.xml" XPath="colors"/>
</StackPanel.Resources>
<Label Content="XML数据绑定"/>
<ListBox Height="100" Margin="0,0,10,0" Name="mylistc" ItemsSource="{Binding Source={StaticResource MyColors},XPath=color/@name}"/>
<Label Content="选中的颜色"/>
<TextBlock TextWrapping="Wrap" Background="YellowGreen" Text="{Binding ElementName=mylistc, Path=SelectedValue, Mode=OneWay}"/>
</StackPanel>
<!--对象绑定-->
<StackPanel Grid.Row="1" Grid.Column="1" HorizontalAlignment="Left" Height="180" Margin="10,10,0,0" VerticalAlignment="Top" Width="466">
<StackPanel.Resources>
<!--ObjectType 指定将提供数据绑定源的对象,而 MethodName 则指示为获得数据而调用的方法-->
<ObjectDataProvider x:Key="students" ObjectType="{x:Type local:StudentService}" MethodName="GetStudentList"/>
<!--DataTemplate数据模板,允许定义自己的显示样式-->
<DataTemplate x:Key="studentLayout" DataType="students">
<StackPanel Orientation="Horizontal" Height="28" Width="244">
<TextBlock Text="{Binding Path=Name}" FontWeight="Bold" Foreground="Blue"/>
<TextBlock Text=", "></TextBlock>
<TextBlock Text="{Binding Path=Birthday}"></TextBlock>
<TextBlock Text=", "></TextBlock>
<TextBlock Text="{Binding Path=Age}"></TextBlock>
<TextBlock Text=", "></TextBlock>
<TextBlock Text="{Binding Path=Country}" FontWeight="Bold" Foreground="red"></TextBlock>
</StackPanel>
</DataTemplate>
</StackPanel.Resources>
<Label Content="对象绑定" HorizontalAlignment="Left" Margin="16,4,0,0" VerticalAlignment="Top"/>
<!--ItemTemplate指定显示样式 ,ItemsSource指定显示来源,IsSynchronizedWithCurrentItem表示异步检索数据-->
<ListBox Name="mylistd" Width="450" Height="147" IsSynchronizedWithCurrentItem="True"
ItemsSource="{Binding Source={StaticResource students}}" ItemTemplate="{DynamicResource studentLayout}" Margin="8,0">
</ListBox>
</StackPanel>
<!--数据排序-->
<StackPanel HorizontalAlignment="Left" Height="264" Margin="10,10,0,0" Grid.Row="2" VerticalAlignment="Top" Width="466">
<StackPanel.Resources>
<ObjectDataProvider x:Key="persons" ObjectType="{x:Type local:PersonService}" MethodName="GetPersonList"/>
<DataTemplate x:Key="personsLayout" DataType="persons">
<StackPanel Orientation="Horizontal" Height="28" Width="244">
<TextBlock Text="{Binding Path=Name}" FontWeight="Bold" Foreground="Blue"/>
<TextBlock Text=", "></TextBlock>
<TextBlock Text="{Binding Path=Birthday}"></TextBlock>
<TextBlock Text=", "></TextBlock>
<TextBlock Text="{Binding Path=Age}"></TextBlock>
<TextBlock Text=", "></TextBlock>
<TextBlock Text="{Binding Path=Country}" FontWeight="Bold" Foreground="red"></TextBlock>
</StackPanel>
</DataTemplate>
<CollectionViewSource x:Key="personsView" Source="{Binding Source={StaticResource persons}}">
<!--排序字段及方式:姓名升序,年龄降序-->
<CollectionViewSource.SortDescriptions >
<scm:SortDescription PropertyName="Name" Direction="Descending"/>
<scm:SortDescription PropertyName="Age" Direction="Ascending" />
</CollectionViewSource.SortDescriptions >
</CollectionViewSource>
</StackPanel.Resources>
<Label Content="数据排序"/>
<!--DataContext指定使用前面定义的数据源personsView-->
<DataGrid Height="100" DataContext="{StaticResource personsView}" AutoGenerateColumns="False" ItemsSource="{Binding}" CanUserAddRows="False">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Name}" Header="名称" />
<DataGridTextColumn Binding="{Binding Age}" Header="年龄" />
<DataGridTextColumn Binding="{Binding Country}" Header="国家" />
<DataGridTextColumn Binding="{Binding Birthday}" Header="出生日期" />
</DataGrid.Columns>
</DataGrid>
</StackPanel>
</Grid>
</Window>
注意在上面添加了命名空间的描述:
xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase"
效果如下:
相当的管用漂亮,继续卷起。
WPF真入门教程20--数据排序相关推荐
- WPF真入门教程02--新建WPF工程
在VS开发环境安装完成之后,首先我们先新建一个WPF工程,然后对工程目录结构啥的要有所了解才行. 打开VS2019 工程建好之后,WPF应用程序"会在"引用"里面自动添加 ...
- WPF真入门教程23--MVVM简单介绍
在WPF开发中,经典的编程模式是MVVM,是为WPF量身定做的模式,该模式充分利用了WPF的数据绑定机制,最大限度地降低了Xmal文件和CS文件的耦合度,也就是UI显示和逻辑代码的耦合度,如需要更换界 ...
- WPF真入门教程21--WPF资源系统
WPF资源系统是一种保管一系列对象(如常用的画刷.样式或模版)的简单办法,从而使您更容易地复用这些对象. WPF允许在代码中以及在标记中的各个位置定义资源(如特定的控件或窗口或在整个应用程序中定义). ...
- WPF真入门教程22--样式应用
1.什么是样式 WPF相较于以前学的WinForm,WPF在UI设计与动画方面的炫丽是最吸引我来学习的.在WPF中XMAL代码的引入使得代码的编写能够前后端分离,为获得更好的界面,也使得我们不得不分出 ...
- WPF真入门教程03--XAML介绍
一.窗体类基本概念 对于WPF应用程序,在Visual Studio和Expression Blend中,自定义的窗体均继承System.Windows.Window类.用户通过窗口与 Windows ...
- WPF真入门教程12--ListView控件
ListView 控件在Windows应用程序中常用,用于表示数据列表.如果您以前使用过 WinForms,那么您对ListView的实用性有一个很好的了解,但您应该意识到 WPF中的ListView ...
- WPF真入门教程01--WPF简介
Windows Presentation Foundation (简称 WPF),WPF是微软推出的基于Windows 的用户界面框架,属于.NET Framework 3.0的一部分.它提供了统一的 ...
- WPF真入门教程04--UI布局1
大家都知道:UI是做好一个软件很重要的因素,如果没有一个漂亮的UI,功能做的再好也无法吸引很多用户使用,而且没有漂亮的界面,那么普通用户会感觉这个软件没有多少使用价值. WPF系统基于流布局的标准,开 ...
- Numpy入门教程:06. 排序,搜索和计数
背景 什么是 NumPy 呢? NumPy 这个词来源于两个单词 – Numerical和Python.其是一个功能强大的 Python 库,可以帮助程序员轻松地进行数值计算,通常应用于以下场景: 执 ...
最新文章
- hdu 5099 Comparison of Android versions 枚举题意
- Swift的控制转移语句-- fallthrough语句
- 想拿下互联网大厂OFFER,都需要准备什么?
- 使用JMeter对异步HTTP / REST服务进行压力/负载测试
- C# 谈谈Interface和通过Interface传递web页面数据
- dns迭代查询配置_人人都能看懂-关于dns服务基本知识
- 进程的创建-Process子类(python 版)
- pandas Dataframe删除缺失值
- sqlite的联表查询-转
- 黑客攻防技术宝典web实战篇:利用信息泄露习题
- 【通信4.0 重新发明通信网】读后感
- 兄弟打印机打印时显示服务器内部错误,打印机出现内部错误无法打印什么原因...
- A Deep Q-Network for the Beer Game: A Reinforcement Learning Algorithm to Solve Inventory Optimizati
- handsome主题添加服务器信息,Typecho handsome主题一言接口修改,使用自己的一言服务...
- [b2g] firefoxOS 移植记录
- 批量生成图片的数据增强常用的脚本
- 第39级台阶 小明刚刚看完电影《第39级台阶》,离开电影院的时候,他数了数礼堂前的台阶数,恰好是39级!
- echarts之toolbox-x,y
- 【css滤镜】高级属性filter
- C# CAD操作之定位实体位置(视图操作缩放)
热门文章
- 两字母.com域名交易频繁,这是要大爆发的节奏
- 7.2某地刑侦大队对涉及六个嫌疑人的一桩疑案进行分析: A、B 至少有一人作案; A、E、F 三人中至少有两人参与作案; A、D 不可能是同案犯; B、C 或同时作案,或与本案无关;
- 一文带你了解火爆的区块链互联网Cosmos
- html文字注释,css如何注释?
- html中鱼眼效果,鱼眼效果和放大效果怎么做
- echarts中的地图与Axure交互
- 服务器主机外接显示器,服务器主机连接显示器
- SDNU 1543.Happy Salted Fish Every Day
- java 变量不初始化_Java之哪些情况下变量不会初始化
- 黑群辉安装php,黑群晖从装机到使用全过程 篇五:群晖安装VirtualBox虚拟机