WPF教程(十一)---数据绑定(4)--数据类绑定

news2024/9/21 14:29:45

一、排序


如果想以特定的方式对数据进行排序,可以绑定到 CollectionViewSource,而不是直接绑定到 ObjectDataProvider。CollectionViewSource 则会成为数据源,并充当截取 ObjectDataProvider 中的数据的媒介,并提供排序、分组和筛选功能,然后将它(排序的数据)传送到目标控件。
这个显示是使用 CollectionViewSource做为排序的数据源,首先将CollectionViewSource的Source 属性设置为 ObjectDataProvider的资源名称。然后通过设置CollectionViewSource.SortDescriptions属性,指定排序字段和排序顺序:

  <CollectionViewSource x:Key="studentsView" Source="{Binding Source={StaticResource students}}">
                    <CollectionViewSource.SortDescriptions>
                        <scm:SortDescription PropertyName="Name" Direction="Ascending" />
                        <scm:SortDescription PropertyName="Age" Direction="Descending" />
                    </CollectionViewSource.SortDescriptions>
                </CollectionViewSource>  

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

  StackPanel的 DataContext 属性绑定了数据源,DataGrid就可以不必再次绑定了(从属关系),直接使用StackPanel绑定的数据源

<StackPanel DataContext="{StaticResource studentsView}">
            <TextBlock Width="248" Height="24" Text="数据排序:"
        TextWrapping="Wrap"/>
            <DataGrid  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>

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

这里写图片描述

 XAML部分:

<Window x:Class="WpfApp4.Window1"
        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:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase"

        xmlns:local="clr-namespace:WpfApp4"
        mc:Ignorable="d"
        Title="Window1" Height="700" Width="500">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="140"/>
            <RowDefinition Height="150"/>
            <RowDefinition Height="140"/>
            <RowDefinition Height="100*"/>
        </Grid.RowDefinitions>
        <StackPanel Grid.Row="0">
            <TextBlock Width="248" Height="24" Text="股票名称:" TextWrapping="Wrap"/>
            <ListBox x:Name="listStockName" Width="248" Height="56">
                <ListBoxItem Content="全通教育"/>
                <ListBoxItem Content="大智慧"/>
                <ListBoxItem Content="宝钢股份"/>
                <ListBoxItem Content="浦发银行"/>
                <ListBoxItem Content="工商银行"/>
                <ListBoxItem Content="中国建筑"/>
                <ListBoxItem Content="中国南车"/>
            </ListBox>
            <TextBlock Width="248" Height="24" Text="你所选中的股票名称:" />
            <TextBlock Width="248" Height="24" Text="{Binding ElementName=listStockName, Path=SelectedItem.Content}">
            </TextBlock>
        </StackPanel>

        <StackPanel Grid.Row="1">
            <TextBlock Width="248" Height="24" Text="颜色:" TextWrapping="Wrap"/>
            <ListBox x:Name="listColor" Width="248" Height="56">
                <ListBoxItem Content="Blue"/>
                <ListBoxItem Content="Red"/>
                <ListBoxItem Content="Green"/>
                <ListBoxItem Content="Gray"/>
                <ListBoxItem Content="Cyan"/>
                <ListBoxItem Content="GreenYellow"/>
                <ListBoxItem Content="Orange"/>
            </ListBox>
            <TextBlock Width="248" Height="24" Text="改变背景色:" />
            <TextBlock Width="248" Height="24" Text="{Binding ElementName=listColor, Path=SelectedItem.Content, Mode=OneWay}"
                       Background="{Binding ElementName=listColor, Path=SelectedItem.Content, Mode=OneWay}">
            </TextBlock>
            <TextBox Name="txtTwoWay" Text="{Binding ElementName=listColor,Path=SelectedItem.Content,Mode=TwoWay}"
                     Background="{Binding ElementName=listColor,Path=SelectedItem.Content,Mode=TwoWay}"></TextBox>
        </StackPanel>


        <StackPanel Grid.Row="2">
            <StackPanel.Resources>
                <XmlDataProvider x:Key="MyColors"  Source="Colors.xml"  XPath="colors">
                </XmlDataProvider>
            </StackPanel.Resources>
            <TextBlock Width="248" Height="24" Text="XML数据绑定:"
        TextWrapping="Wrap"/>
            <ListBox x:Name="listXmlColor" Width="248" Height="56" IsSynchronizedWithCurrentItem="True"
                     ItemsSource="{Binding Source={StaticResource MyColors},XPath=color/@name}">
            </ListBox>
            <TextBlock Width="248" Height="24" Text="选中的颜色:" />
            <TextBlock Width="248" Height="24" Text="{Binding ElementName=listXmlColor,  Path=SelectedValue, Mode=OneWay}">
            </TextBlock>
        </StackPanel>

        <StackPanel Grid.Row="3">
            <StackPanel.Resources>
                <ObjectDataProvider x:Key="students"  ObjectType="{x:Type local:StudentService}" MethodName="GetStudentList">
                </ObjectDataProvider>
                <DataTemplate x:Key="studentLayout" DataType="students">
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="{Binding Path=Name}"
                            FontWeight="Bold" Foreground="Blue"/>
                        <TextBlock Text=", "></TextBlock>
                        <TextBlock Text="{Binding Path=Age}"></TextBlock>
                        <TextBlock Text=", "></TextBlock>
                        <TextBlock Text="{Binding Path=Birthday}"></TextBlock>
                        <TextBlock Text=", "></TextBlock>
                        <TextBlock Text="{Binding Path=Country}"></TextBlock>
                    </StackPanel>
                </DataTemplate>
                <CollectionViewSource x:Key="studentsView" Source="{Binding Source={StaticResource students}}">
                    <CollectionViewSource.SortDescriptions>
                        <scm:SortDescription PropertyName="Name" Direction="Ascending" />
                        <scm:SortDescription PropertyName="Age" Direction="Descending" />
                    </CollectionViewSource.SortDescriptions>
                </CollectionViewSource>
            </StackPanel.Resources>
            <TextBlock Width="248" Height="24" Text="对象数据绑定:"
        TextWrapping="Wrap"/>
            <ListBox x:Name="listObjectBind" Width="450" Height="80" IsSynchronizedWithCurrentItem="True"
                     ItemsSource="{Binding Source={StaticResource students}}"
                     ItemTemplate="{DynamicResource studentLayout}">
            </ListBox>
            <TextBlock Width="248" Height="24" Text="数据排序:"
        TextWrapping="Wrap"/>
            <DataGrid DataContext="{StaticResource studentsView}" 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>

数据类代码部分:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace WpfApp4
{
    public class Student : DependencyObject
    {
    //声明一个静态只读的依赖属性DependencyProperty字段
    public static readonly DependencyProperty NameProperty;
    public static readonly DependencyProperty AgeProperty;
    public static readonly DependencyProperty BirthdayProperty;
    public static readonly DependencyProperty CountryProperty;
    static Student()
    {
       //创建依赖属性
       //注册我们定义的依赖属性Name,Age,birthday,Country
       NameProperty = DependencyProperty.Register("Name", typeof(string), typeof(Student), new PropertyMetadata("名称", OnValueChanged));
        AgeProperty = DependencyProperty.Register("Age", typeof(string), typeof(Student), new PropertyMetadata("年龄", OnValueChanged));
        BirthdayProperty = DependencyProperty.Register("Birthday", typeof(string), typeof(Student),new PropertyMetadata("出生日期", OnValueChanged));
        CountryProperty = DependencyProperty.Register("Country", typeof(string), typeof(Student), 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); }
    }
    }
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/447914.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

PMP项目管理-[第六章]进度管理

进度管理知识体系&#xff1a; 规划进度管理&#xff1a; 定义活动&#xff1a; 排列活动顺序&#xff1a; 估算活动持续时间&#xff1a; 制定进度计划&#xff1a; 6.1 规划进度管理 定义&#xff1a;为规划、编制、管理、执行和控制项目进度而制定政策、程序和文档的过程 作…

docker简单教程(三)常用操作

docker简单教程&#xff08;三&#xff09;常用操作 文章目录 docker简单教程&#xff08;三&#xff09;常用操作1&#xff1a;查看所有容器列表&#xff1a;docker ps -a2&#xff1a;查看正在运行的容器列表&#xff1a;docker ps3&#xff1a;运行容器&#xff1a;docker r…

内网渗透之横向移动wmismb密码喷射CrackMapExec

0x01 横向移动之wmi wmi可以通过hash或明文进行验证&#xff0c;不会在系统日志中留下痕迹&#xff0c;使用139端口 复现环境&#xff1a; god.org win2008 dc win2012sql win2008 web 准备&#xff1a; cs上线 win2008web 提权利用ms14-058 抓取hash和明文密码(当获取到其他…

重磅发布,时隔两月——复旦大学MOSS最新0.0.3版本发布

今天中午吃饭的时候无意间看到一则新闻说的就是复旦大学开发的MOSS也就是国产版的类chatGPT对话模型已经发布了最新版本0。0.3&#xff0c;目前公测期间是完全开源免费的&#xff0c;还是可以上手体验一下的。 官方的博客介绍在这里&#xff0c;首页如下所示&#xff1a; 如果…

手机端无线投屏技术及方案推荐

目前主流的无线投屏技术主要又DLNA&#xff0c;Miracast&#xff0c;Airplay。 对协议的描述引用知乎作者的文章&#xff0c;原文&#xff1a;AirPlay、Miracast 、DLNA三大协议对比 - 知乎 (zhihu.com) 【DLNA】 DNLA&#xff0c;Digital Living Network Alliance&#xff…

光照的个人推导过程与GL实现

目录 1、前提知识 1.1、GL的绘图过程&#xff1a; 1.2、点积的规则和作用&#xff1a; 1.3、normalize在方向处理上的作用 2、光照控制的理论基础 2.1、自由的实现&#xff1a; 2.2、带有方向性的光——基于dot product的实现 最终效果演示如下&#xff1a; 3、关键代…

可能是史上最详细的MySQL用户和权限原理和实战

前言 MySQL是一个关系型数据库管理系统&#xff0c;由瑞典MySQL AB 公司开发&#xff0c;属于 Oracle 旗下产品。MySQL是最流行的关系型数据库管理系统之一&#xff0c;在 WEB 应用方面&#xff0c;MySQL是最好的 RDBMS (Relational Database Management System&#xff0c;关系…

Python - Jupyter - 远程连接Jupyter内核

Python - Jupyter - 远程连接Jupyter内核 前言 假设你有一台高性能服务器&#xff08;电脑B&#xff09;&#xff0c;并且在上面安装好了Jupyter 现在你想使用你自己常用的电脑&#xff08;电脑A&#xff09;编码&#xff0c;但使用电脑B的计算资源。 怎么办呢&#xff1f;…

WPS以普通会员价格升级超级会员

文章目录 一、新会员体系二、基本原理三、升级超级会员1、购买会员时长2、成功通知3、兑换时长 一、新会员体系 4月17日&#xff0c;WPS会员体系全新升级。本次升级&#xff0c;WPS将原“WPS会员”、“稻壳会员”及“超级会员”合并、升级&#xff0c;推出全新的“WPS超级会员…

235:vue+openlayers 绘制带有径向渐变填充色的圆形

第235个 点击查看专栏目录 本示例的目的是介绍如何在vue+openlayer中绘制带有径向渐变填充色的圆形。 如果填充线性渐变的多边形,可以参考这个篇文章 直接复制下面的 vue+openlayers源代码,操作2分钟即可运行实现效果 文章目录 示例效果配置方式示例源代码(共136行)相关A…

通过python代码自定义ssh密码爆破

通过python代码自定义ssh密码爆破 一&#xff0c;这段代码的意义&#xff1a;二&#xff0c;直接上写好的代码:三&#xff0c;使用pip3 install paramiko 命令安装库四&#xff0c;使用 python3 test.py 主机地址 -u 用户名 -p 字典路径/五&#xff0c;字典的选取 一&#xff0…

RT-DETR的学习笔记

1. RT-DETR GitHub: PaddleDetection/tree/develop/configs/rtdetr 2. 复现训练流程 2.1 原文使用设备 2.2 环境要求 4*v100 cuda 10.2 paddlepaddle-gpu > 2.4.1 2.3 创建conda环境 conda create --name ppdet python3.102.4 安装RT-DETR推荐的paddle版本 前往官网…

4.26和4.27、selectAPI介绍(4.27、select代码)

4.26和4.27、selectAPI介绍&#xff08;4.27、select代码&#xff09; 1.selectAPI介绍①select多路复用流程图②select多路复用缺点 2.select代码使用介绍3.select代码实现①select服务端实现②select客户端实现 1.selectAPI介绍 主旨思想&#xff1a; 首先要构造一个关于文件…

FreeRTOS 其他任务 API 函数

文章目录 一、任务相关 API 函数预览二、任务相关 API 函数详解1. 函数 uxTaskPriorityGet()2. 函数 vTaskPrioritySet()3. uxTaskGetSystemState()4. 函数 vTaskGetInfo()5. 函数 xTaskGetApplicationTaskTag()6. 函数 xTaskGetCurrentTaskHandle()7. 函数 xTaskGetHandle()8.…

(十二)rk3568 NPU 中部署自己训练的模型,(1)使用yolov5训练自己的数据集-模型训练部分

一、rknn的demo中已经给了yolov5的后处理demo。但是这个后处理只适合yolov5特定版本(v5.0),还有下载特定的分支,如下为下载位置:。 下载地址 ONNX > CoreML > TFLite">GitHub - ultralytics/yolov5: YOLOv5 🚀 in PyTorch > ONNX > CoreML > T…

LeetCode 27.移除元素

文章目录 &#x1f4a1;题目分析&#x1f4a1;解题思路&#x1f6a9;思路1:暴力求解 --- 遍历&#x1f514;接口源码&#xff1a;&#x1f6a9;思路2:空间换时间&#x1f514;接口源码&#xff1a;&#x1f6a9;思路3:双指针&#xff08;快慢指针&#xff09;&#x1f514;接口…

Linux系统之部署Samba服务

Linux系统之部署Samba服务 一、Samba服务介绍1.Samba服务简介2.NFS和CIFS简介3.Smaba服务相关包4.samba监听端口4.samba相关工具及命令 二、环境规划介绍1.环境规划2.本次实践介绍 三、Samba服务端配置1.检查yum仓库2.安装smaba相关软件包3.创建共享目录4.设置共享目录权限5.新…

Adobe认证证书

Adobe认证证书是Adobe公司颁发的一种专业认证证书&#xff0c;用于证明持有人在相关Adobe软件的使用和应用方面具有专业水平。该证书是业内公认的专业认证&#xff0c;具有较高的价值和认可度&#xff0c;可以帮助持有人提高职业竞争力和工作效率。 Adobe公司提供了多种认证考…

CentOS7(三)MySQL8 Redis7 (单机)安装

文章目录 一、MySQL安装1、确认是否有老版本2、在线安装3、本地安装 二、启动MySQL三、MySQL常用配置1、密码修改2、配置远程登录3、开启防火墙 3306 端口4、 报错5、MySQL中Java写入时间少14小时 四、Redis 安装1、安装Redis依赖2、启动redis3、指定配置启动 & 后台运行4、…

手机端H5地图调起开发实战案例解析(百度高德腾讯地图调起、底部弹出层、提示安装地图导航APP)

文章目录 1.导航菜单配置构建导航菜单容器设置取消事件调起菜单样式表 2.地图调起事件导航到这里获取导航坐标百度坐标系 (BD-09) 与 火星坐标系 (GCJ-02)的转换 3.地图调起效果 地图调起功能&#xff0c;是地图URI API是为开发者提供直接调起地图产品&#xff08;手机客户端&a…