当前位置: 首页 > news >正文

WPF数据视图

将集合绑定到ItemsControl控件时,会不加通告的在后台创建数据视图——位于数据源和绑定的控件之间。数据视图是进入数据源的窗口,可以跟踪当前项,并且支持各种功能,如排序、过滤、分组。

这些功能和数据对象本身是相互独立的,这意味着可在窗口的不同部分使用不同的方式绑定相同的数据。例如,可将同一个集合绑定到两个不同的列表,并对集合进行过滤以显示不同的记录。(来自于WPF编程宝典。我实测下来,绑定自同一个数据源的ItemsControl控件会共享一个View,当对该View进行筛选、排序时,会应用到所有绑定到该数据源的控件。)

获取视图的方法:

ListCollectionView? view = CollectionViewSource.GetDefaultView(filterListBox.ItemsSource) as ListCollectionView;
ListCollectionView? view = CollectionViewSource.GetDefaultView(Orders) as ListCollectionView;

可以看到,可以直接通过数据源来获取视图,这也表明,绑定到同一个数据源的控件会公用一个视图。

视图有 MoveCurrentToPrevious()、MoveCurrentToNext() 方法,可以用于视图导航。

    private void cmdPrev_Click(object sender, RoutedEventArgs e){View?.MoveCurrentToPrevious();}private void cmdNext_Click(object sender, RoutedEventArgs e){View?.MoveCurrentToNext();}private void view_CurrentChanged(object? sender, EventArgs e){lblPosition.Text = "Record " + (View?.CurrentPosition + 1).ToString() + " of " + View?.Count.ToString();cmdPrev.IsEnabled = View?.CurrentPosition > 0;cmdNext.IsEnabled = View?.CurrentPosition < View?.Count - 1;}

视图排序

View.SortDescriptions.Add(new SortDescription("Volume", ListSortDirection.Ascending));
View.SortDescriptions.Add(new SortDescription("Price", ListSortDirection.Descending));

视图分组

<ListBox x:Name="groupListBox" ItemsSource="{Binding Path=Orders}"><ListBox.ItemTemplate><DataTemplate><TextBlock><TextBlock Text="{Binding Price}"></TextBlock> - <TextBlock Text="{Binding Volume}"></TextBlock></TextBlock></DataTemplate></ListBox.ItemTemplate><ListBox.GroupStyle><GroupStyle><GroupStyle.HeaderTemplate><DataTemplate><TextBlock Text="{Binding Path=Name}" FontWeight="Bold" Foreground="White" Background="LightGreen" Margin="0,5,0,0" Padding="3"/></DataTemplate></GroupStyle.HeaderTemplate></GroupStyle></ListBox.GroupStyle>
</ListBox>
View.GroupDescriptions.Add(new PropertyGroupDescription("Volume"));

视图过滤

public class ProductByPriceFilterer
{public ProductByPriceFilterer(decimal minimumPrice){MinimumPrice = minimumPrice;}public decimal MinimumPrice { get; set; }public bool FilterItem(Object item){Order? order = item as Order;if (order != null){return order.Price > MinimumPrice;}return false;}
}
public partial class MainWindow : Window
{public MainWindow(){InitializeComponent();View = (ListCollectionView)CollectionViewSource.GetDefaultView(Orders);View.IsLiveFiltering = true;View.LiveFilteringProperties.Add("Price");}public ObservableCollection<Order> Orders { get; set; } = new();private ListCollectionView? View;public decimal MinPrice { get; set; } = 200;private ProductByPriceFilterer? filterer;private void cmdFilter_Click(object sender, RoutedEventArgs e){if (View != null){filterer = new ProductByPriceFilterer(MinPrice);View.Filter = new Predicate<object>(filterer.FilterItem);}}private void cmdRemoveFilter_Click(object sender, RoutedEventArgs e){if (View != null){View.Filter = null;}}
}

完整代码文件:

MainWindow.xaml

<Window x:Class="DataView.MainWindow"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:DataView"mc:Ignorable="d"Title="MainWindow" Height="450" Width="800"><Grid Name="myGrid"><Grid.ColumnDefinitions><ColumnDefinition/><ColumnDefinition/></Grid.ColumnDefinitions><Grid.RowDefinitions><RowDefinition/><RowDefinition/><RowDefinition/><RowDefinition Height="Auto"/></Grid.RowDefinitions><StackPanel Grid.Row="0" Grid.Column="0" ><StackPanel Orientation="Horizontal"><Button Name="cmdPrev" Click="cmdPrev_Click">&lt;</Button><TextBlock Name="lblPosition" VerticalAlignment="Center"></TextBlock><Button Name="cmdNext" Click="cmdNext_Click">&gt;</Button></StackPanel><ListBox x:Name="navigateListBox" DisplayMemberPath="Price" IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding Path=Orders}"/></StackPanel><StackPanel Grid.Row="0" Grid.Column="1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"><Grid><Grid.ColumnDefinitions><ColumnDefinition></ColumnDefinition><ColumnDefinition></ColumnDefinition></Grid.ColumnDefinitions><Grid.RowDefinitions><RowDefinition></RowDefinition><RowDefinition></RowDefinition></Grid.RowDefinitions><Label Grid.Row="0" Grid.Column="0">Price > Than</Label><TextBox Grid.Row="0" Grid.Column="1" Text="{Binding Path=MinPrice}"></TextBox><Button Grid.Row="1" Grid.Column="0" Click="cmdFilter_Click">Filter</Button><Button Grid.Row="1" Grid.Column="1" Click="cmdRemoveFilter_Click">Remove Filter</Button></Grid><ListBox Name="filterListBox" DisplayMemberPath="Price" ItemsSource="{Binding Path=Orders}"/></StackPanel><StackPanel Grid.Row="1" Grid.Column="0"><ListBox x:Name="groupListBox" ItemsSource="{Binding Path=Orders}"><ListBox.ItemTemplate><DataTemplate><TextBlock><TextBlock Text="{Binding Price}"></TextBlock> - <TextBlock Text="{Binding Volume}"></TextBlock></TextBlock></DataTemplate></ListBox.ItemTemplate><ListBox.GroupStyle><GroupStyle><GroupStyle.HeaderTemplate><DataTemplate><TextBlock Text="{Binding Path=Name}" FontWeight="Bold" Foreground="White" Background="LightGreen" Margin="0,5,0,0" Padding="3"/></DataTemplate></GroupStyle.HeaderTemplate></GroupStyle></ListBox.GroupStyle></ListBox></StackPanel><Button Grid.Row="2" Grid.Column="0" Content="Increase Price" Click="IncreaseButton_Click"/><Button Grid.Row="2" Grid.Column="1" Content="Decrease Price" Click="DecreaseButton_Click"/></Grid>
</Window>

MainWindow.xaml.cs

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;namespace DataView;public class ViewModelBase : INotifyPropertyChanged
{public event PropertyChangedEventHandler? PropertyChanged;protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null){PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));}protected virtual bool SetProperty<T>(ref T member, T value, [CallerMemberName] string? propertyName = null){if (EqualityComparer<T>.Default.Equals(member, value)){return false;}member = value;OnPropertyChanged(propertyName);return true;}
}
public class Order : ViewModelBase
{public decimal price = 0;public decimal Price { get => price; set => SetProperty(ref price, value); }public int volume = 0;public int Volume { get => volume; set => SetProperty(ref volume, value); }public DateTime orderDate = DateTime.Now;public DateTime OrderDate { get => orderDate; set => SetProperty(ref orderDate, value); }public string image = string.Empty;public string Image { get => image; set => SetProperty(ref image, value); }
}
public class ProductByPriceFilterer
{public ProductByPriceFilterer(decimal minimumPrice){MinimumPrice = minimumPrice;}public decimal MinimumPrice { get; set; }public bool FilterItem(Object item){Order? order = item as Order;if (order != null){return order.Price > MinimumPrice;}return false;}
}
public class PriceRangeProductGrouper : IValueConverter
{public int GroupInterval { get; set; }public object Convert(object value, Type targetType, object parameter, CultureInfo culture){decimal price = (decimal)value;if (price < GroupInterval){return string.Format("Less than {0:C}", GroupInterval);}else{int interval = (int)price / GroupInterval;int lowerLimit = interval * GroupInterval;int upperLimit = (interval + 1) * GroupInterval;return string.Format("{0:C} to {1:C}", lowerLimit, upperLimit);}}public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture){throw new NotSupportedException("This converter is for grouping only.");}
}
public partial class MainWindow : Window
{public MainWindow(){InitializeComponent();myGrid.DataContext = this;InitOrders();InitView();}public void InitOrders(){Order order1 = new Order();Order order2 = new Order();Order order3 = new Order();Order order4 = new Order();order1.Price = 100;order1.Volume = 100;order1.Image = "image1.gif";order2.Price = 1000;order2.Volume = 100;order2.Image = "image2.gif";order3.Price = 10000;order3.Volume = 10000;order3.Image = "image3.gif";order4.Price = 100000;order4.Volume = 10000;order4.Image = "image4.gif";Orders.Add(order1);Orders.Add(order2);Orders.Add(order3);Orders.Add(order4);}private void InitView(){View = (ListCollectionView)CollectionViewSource.GetDefaultView(Orders);if(View != null){View.CurrentChanged += new EventHandler(view_CurrentChanged);View.SortDescriptions.Add(new SortDescription("Volume", ListSortDirection.Ascending));View.SortDescriptions.Add(new SortDescription("Price", ListSortDirection.Descending));View.GroupDescriptions.Add(new PropertyGroupDescription("Volume"));View.IsLiveFiltering = true;View.LiveFilteringProperties.Add("Price");}}public ObservableCollection<Order> Orders { get; set; } = new();private ListCollectionView? View;private void cmdPrev_Click(object sender, RoutedEventArgs e){View?.MoveCurrentToPrevious();}private void cmdNext_Click(object sender, RoutedEventArgs e){View?.MoveCurrentToNext();}private void view_CurrentChanged(object? sender, EventArgs e){lblPosition.Text = "Record " + (View?.CurrentPosition + 1).ToString() + " of " + View?.Count.ToString();cmdPrev.IsEnabled = View?.CurrentPosition > 0;cmdNext.IsEnabled = View?.CurrentPosition < View?.Count - 1;}public decimal MinPrice { get; set; } = 200;private ProductByPriceFilterer? filterer;private void cmdFilter_Click(object sender, RoutedEventArgs e){if (View != null){filterer = new ProductByPriceFilterer(MinPrice);View.Filter = new Predicate<object>(filterer.FilterItem);}}private void cmdRemoveFilter_Click(object sender, RoutedEventArgs e){if (View != null){View.Filter = null;}}private void IncreaseButton_Click(object sender, RoutedEventArgs e){foreach(var order in Orders){order.Price *= 10;}}private void DecreaseButton_Click(object sender, RoutedEventArgs e){foreach (var order in Orders){order.Price /= 10;}}
}

相关文章:

WPF数据视图

将集合绑定到ItemsControl控件时&#xff0c;会不加通告的在后台创建数据视图——位于数据源和绑定的控件之间。数据视图是进入数据源的窗口&#xff0c;可以跟踪当前项&#xff0c;并且支持各种功能&#xff0c;如排序、过滤、分组。 这些功能和数据对象本身是相互独立的&…...

C++ new/delete 与 malloc/free 的区别?

new/delete 与 malloc/free 的区别&#xff1f; 分配内存的位置 malloc是从堆上动态分配内存new是从自由存储区为对象动态分配内存。自由存储区的位置取决于operator new的实现。自由存储区不仅可以为堆&#xff0c;还可以是静态存储区&#xff0c;这都看operator new在哪里为…...

【数学建模】常微分,偏微分方程

1.常微分方程 普通边界 已知t0时刻的初值 ode45() 龙格-库塔法 一阶&#xff0c;高阶都一样 如下: s(1) y , s(2)y s(3) x , s(4)x //匿名函数 下为方程组 核心函数 s_chuzhi [0;0;0;0]; //初值 分别两个位移和速度的初值 t0 0:0.2:180; f (t,s)[s(2);(…...

浙大数据结构之09-排序1 排序

题目详情&#xff1a; 给定N个&#xff08;长整型范围内的&#xff09;整数&#xff0c;要求输出从小到大排序后的结果。 本题旨在测试各种不同的排序算法在各种数据情况下的表现。各组测试数据特点如下&#xff1a; 数据1&#xff1a;只有1个元素&#xff1b;数据2&#xf…...

Pydantic 学习随笔

这里是零散的记录一些学习过程中随机的理解&#xff0c;因此这里的记录不成体系。如果是想学习 Pydantic 建议看官方文档&#xff0c;写的很详细并且成体系。如果有问题需要交流&#xff0c;欢迎私信或者评论。 siwa 报 500 Pydantic 可以和 siwa 结合使用&#xff0c;这样既…...

11 mysql float/double/decimal 的数据存储

前言 这里主要是 由于之前的一个 datetime 存储的时间 导致的问题的衍生出来的探究 探究的主要内容为 int 类类型的存储, 浮点类类型的存储, char 类类型的存储, blob 类类型的存储, enum/json/set/bit 类类型的存储 本文主要 的相关内容是 float, decimal 类类型的相关数据…...

【高效数据结构——位图bitmap】

初识位图bitmap 位图&#xff08;Bitmap&#xff09;是一种用于表示和操作位&#xff08;bit&#xff09;的数据结构。它是由一系列二进制位&#xff08;0 或 1&#xff09;组成的序列&#xff0c;每个位都可以单独访问和操作。 位图常用于以下情况&#xff1a; 压缩存储&…...

ArrayList LinkedList

ArrayList 和 LinkedList 区别 ArrayList和LinkedList都是Java集合框架中的实现类&#xff0c;用于存储和操作数据。它们在底层实现和性能特点上有一些区别。 数据结构&#xff1a;ArrayList底层使用数组实现&#xff0c;而LinkedList底层使用双向链表实现。这导致它们在内存结…...

iOS砸壳系列之三:Frida介绍和使用

当涉及从App Store下载应用程序时&#xff0c;它们都是已安装的iOS应用&#xff08;IPA&#xff09;存储在设备上。这些应用程序通常带有保护的代码和资源&#xff0c;以限制用户对其进行修改或者逆向工程。 然而&#xff0c;有时候&#xff0c;为了进行调试、制作插件或者学习…...

Git学习——细节补充

Git学习——细节补充 1. git diff2. git log3. git reset4. git reflog5. 提交撤销5.1 当你改乱了工作区某个文件的内容&#xff0c;想直接丢弃工作区的修改时5.2 当提交到了stage区后&#xff0c;想要退回 6. git remote7. git pull origin master --no-rebase8. 分支管理9. g…...

【设计模式】Head First 设计模式——装饰者模式 C++实现

设计模式最大的作用就是在变化和稳定中间寻找隔离点&#xff0c;然后分离它们&#xff0c;从而管理变化。将变化像小兔子一样关到笼子里&#xff0c;让它在笼子里随便跳&#xff0c;而不至于跳出来把你整个房间给污染掉。 设计思想 动态地将责任附加到对象上&#xff0c;若要扩…...

layui实现数据列表的复选框回显

layui版本2.8以上 实现效果如图&#xff1a; <input type"hidden" name"id" id"id" value"{:g_val( id,0)}"> <div id"tableDiv"><table class"layui-hide" id"table_list" lay-filter…...

关于使用RT-Thread系统读取stm32的adc无法连续转换的问题解决

关于使用RT-Thread系统读取stm32的adc无法连续转换的问题解决 今天发现rt系统的adc有一个缺陷&#xff08;也可能是我移植的方法有问题&#xff0c;这就不得而知了&#xff01;&#xff09;&#xff0c;就是只能单次转换&#xff0c;事情是这样的&#xff1a; 我在stm32的RT-T…...

【启扬方案】启扬多尺寸安卓屏一体机,助力仓储物料管理系统智能化管理

随着企业供应链管理的不断发展&#xff0c;对仓储物料管理的要求日益提高。企业需要实时追踪和管理物料的流动&#xff0c;提高物流效率、降低库存成本和减少库存的风险。因此&#xff0c;仓储物料管理系统的实现成为必要的手段。 仓储物料管理系统一体机作为一种新型的物料管理…...

Android Glide使用姿势与原理分析

作者&#xff1a; 午后一小憩 简介 Android Glide是一款强大的图片加载库&#xff0c;提供了丰富的功能和灵活的使用方式。本文将深入分析Glide的工作原理&#xff0c;并介绍一些使用姿势&#xff0c;助你更好地运用这个优秀的库。 原理分析 Glide的原理复杂而高效。它首先基…...

管理类联考——逻辑——汇总篇——知识点突破——形式逻辑——联言选言——真假

角度——真值表 以上考点均是已知命题的真假情况做出的推理,还存在一种情况是已知肢判断P、Q的真假,断定干判断的真假,这种判断过程就是运用真值表。 P ∧ Q的真值 ①如何证明P ∧ Q为假? 由于P ∧ Q的本质是P、Q同时成立,所以只要P、Q有一个为假,整个命题就为假。 ②如…...

ChatGPT数据分析及作图插件推荐-Code Interpreter

今天打开chatGPT时发现一个重磅更新&#xff01;code interpreter插件可以使用了。 去查看openai官网&#xff0c;发现从2023.7.6号&#xff08;前天&#xff09;开始&#xff0c;code interpreter插件已经面向所有chatGPT plus用户开放了。 为什么说code interpreter插件是一…...

说说FLINK细粒度滑动窗口如何处理

分析&回答 Flink的窗口机制是其底层核心之一&#xff0c;也是高效流处理的关键。Flink窗口分配的基类是WindowAssigner抽象类&#xff0c;下面的类图示出了Flink能够提供的所有窗口类型。 Flink窗口分为滚动&#xff08;tumbling&#xff09;、滑动&#xff08;sliding&am…...

记一次反弹shell的操作【非常简单】

#什么是反弹shell 通常我们对一个开启了80端口的服务器进行访问时&#xff0c;就会建立起与服务器Web服务链接&#xff0c;从而获取到服务器相应的Web服务。而反弹shell是我们开启一个端口进行监听&#xff0c;转而让服务器主动反弹一个shell来连接我们的主机&#xff0c;我们再…...

如何排查 Flink Checkpoint 失败问题?

分析&回答 这是 Flink 相关工作中最常出现的问题&#xff0c;值得大家搞明白。 1. 先找到超时的subtask序号 图有点问题&#xff0c;因为都是成功没失败的&#xff0c;尴尬了。 借图&#xff1a; 2. 找到对应的机器和任务 方法很多&#xff0c;这里看自己习惯和公司提供…...

Auto-Coder使用GPT-4o完成:在用TabPFN这个模型构建一个预测未来3天涨跌的分类任务

通过akshare库&#xff0c;获取股票数据&#xff0c;并生成TabPFN这个模型 可以识别、处理的格式&#xff0c;写一个完整的预处理示例&#xff0c;并构建一个预测未来 3 天股价涨跌的分类任务 用TabPFN这个模型构建一个预测未来 3 天股价涨跌的分类任务&#xff0c;进行预测并输…...

五年级数学知识边界总结思考-下册

目录 一、背景二、过程1.观察物体小学五年级下册“观察物体”知识点详解&#xff1a;由来、作用与意义**一、知识点核心内容****二、知识点的由来&#xff1a;从生活实践到数学抽象****三、知识的作用&#xff1a;解决实际问题的工具****四、学习的意义&#xff1a;培养核心素养…...

GitHub 趋势日报 (2025年06月08日)

&#x1f4ca; 由 TrendForge 系统生成 | &#x1f310; https://trendforge.devlive.org/ &#x1f310; 本日报中的项目描述已自动翻译为中文 &#x1f4c8; 今日获星趋势图 今日获星趋势图 884 cognee 566 dify 414 HumanSystemOptimization 414 omni-tools 321 note-gen …...

MySQL账号权限管理指南:安全创建账户与精细授权技巧

在MySQL数据库管理中&#xff0c;合理创建用户账号并分配精确权限是保障数据安全的核心环节。直接使用root账号进行所有操作不仅危险且难以审计操作行为。今天我们来全面解析MySQL账号创建与权限分配的专业方法。 一、为何需要创建独立账号&#xff1f; 最小权限原则&#xf…...

【电力电子】基于STM32F103C8T6单片机双极性SPWM逆变(硬件篇)

本项目是基于 STM32F103C8T6 微控制器的 SPWM(正弦脉宽调制)电源模块,能够生成可调频率和幅值的正弦波交流电源输出。该项目适用于逆变器、UPS电源、变频器等应用场景。 供电电源 输入电压采集 上图为本设计的电源电路,图中 D1 为二极管, 其目的是防止正负极电源反接, …...

C#学习第29天:表达式树(Expression Trees)

目录 什么是表达式树&#xff1f; 核心概念 1.表达式树的构建 2. 表达式树与Lambda表达式 3.解析和访问表达式树 4.动态条件查询 表达式树的优势 1.动态构建查询 2.LINQ 提供程序支持&#xff1a; 3.性能优化 4.元数据处理 5.代码转换和重写 适用场景 代码复杂性…...

Redis:现代应用开发的高效内存数据存储利器

一、Redis的起源与发展 Redis最初由意大利程序员Salvatore Sanfilippo在2009年开发&#xff0c;其初衷是为了满足他自己的一个项目需求&#xff0c;即需要一个高性能的键值存储系统来解决传统数据库在高并发场景下的性能瓶颈。随着项目的开源&#xff0c;Redis凭借其简单易用、…...

【 java 虚拟机知识 第一篇 】

目录 1.内存模型 1.1.JVM内存模型的介绍 1.2.堆和栈的区别 1.3.栈的存储细节 1.4.堆的部分 1.5.程序计数器的作用 1.6.方法区的内容 1.7.字符串池 1.8.引用类型 1.9.内存泄漏与内存溢出 1.10.会出现内存溢出的结构 1.内存模型 1.1.JVM内存模型的介绍 内存模型主要分…...

【堆垛策略】设计方法

堆垛策略的设计是积木堆叠系统的核心&#xff0c;直接影响堆叠的稳定性、效率和容错能力。以下是分层次的堆垛策略设计方法&#xff0c;涵盖基础规则、优化算法和容错机制&#xff1a; 1. 基础堆垛规则 (1) 物理稳定性优先 重心原则&#xff1a; 大尺寸/重量积木在下&#xf…...

前端高频面试题2:浏览器/计算机网络

本专栏相关链接 前端高频面试题1&#xff1a;HTML/CSS 前端高频面试题2&#xff1a;浏览器/计算机网络 前端高频面试题3&#xff1a;JavaScript 1.什么是强缓存、协商缓存&#xff1f; 强缓存&#xff1a; 当浏览器请求资源时&#xff0c;首先检查本地缓存是否命中。如果命…...