WPF-19 IValueConverter接口

我们先来看看微软官方给出的定语:提供将自定义逻辑应用于绑定的方法,我们来看一下该接口的定义,Convert提供了将数据源到UI的格式化,ConvertBack表示反向

namespace System.Windows.Data
{//// Summary://     Provides a way to apply custom logic to a binding.public interface IValueConverter{object Convert(object value, Type targetType, object parameter, CultureInfo culture);object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture);}
}

我们做一个简单的例子实现商品列表的绑定,定义一个DecimalConverter数据转化接口来实现一个价格的格式化,我们将价格格式化成两位小数:

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media;
namespace Example_17
{/// <summary>/// Interaction logic for MainWindow.xaml/// </summary>public partial class MainWindow : Window{public MainWindow(){InitializeComponent();this.Loaded += MainWindow_Loaded;}private void MainWindow_Loaded(object sender, RoutedEventArgs e){List<Order> orders = new List<Order>();Order order = new Order();order.Merchindise = "IPhone 14";order.Quantity = 1;order.Price = 8000;orders.Add(order);order = new Order();order.Merchindise = "卫生纸";order.Quantity = 10;order.Price = 28.7895M;orders.Add(order);order = new Order();order.Merchindise = "笔记本";order.Quantity = 10;order.Price = 87.7895M;orders.Add(order);this.lstOrder.ItemsSource = orders;}}[ValueConversion(typeof(decimal), typeof(string))]public class DecimalConverter : IValueConverter{public object? Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture){if (value != null)return ((decimal)value).ToString("f2");elsereturn null;}public object? ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture){return null;}}public class Order{public string Merchindise { get; set; } = null!;public int Quantity { get; set; }public decimal Price { get; set; }}
}
<Window x:Class="Example_17.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:Example_17"mc:Ignorable="d" Title="MainWindow" Height="450" Width="800"><Window.Resources><local:DecimalConverter x:Key="myDecimalConverter"></local:DecimalConverter></Window.Resources><StackPanel x:Uid="staOrder"><ListView x:Uid="lstOrder" IsSynchronizedWithCurrentItem="True" ScrollViewer.CanContentScroll="True" x:Name="lstOrder" AllowDrop="True" BorderThickness="0,0,0,1" Focusable="False"><ListView.View><GridView x:Uid="GridView_1"><GridViewColumn x:Name="colMerchindise" x:Uid="GridViewColumn_1" Header="商品名称" Width="250"><GridViewColumn.CellTemplate><DataTemplate><Border Width="138" Height="Auto"><Grid x:Uid="Grid_2" Height="Auto" Width="Auto"><TextBlock x:Uid="TextBlock_2" Margin="0,0,0,0" HorizontalAlignment="Left"  VerticalAlignment="Stretch" Text="{Binding Path=Merchindise}" FontFamily="Arial" FontWeight="Bold" FontSize="15" TextWrapping="NoWrap" TextTrimming="WordEllipsis" /></Grid></Border></DataTemplate></GridViewColumn.CellTemplate></GridViewColumn><GridViewColumn x:Name="colQuantity" x:Uid="GridViewColumn_2" Header="数量" Width="170" ><GridViewColumn.CellTemplate><DataTemplate><Border Width="56" Height="Auto"><Grid x:Uid="Grid_3" Height="Auto" Width="Auto"><TextBlock x:Uid="TextBlock_3" Margin="0,0,0,0" Text="{Binding Path=Quantity}" HorizontalAlignment="Right" VerticalAlignment="Center"  FontFamily="Arial" FontWeight="Bold" FontSize="15" Background="{x:Null}" TextTrimming="WordEllipsis" /></Grid></Border></DataTemplate></GridViewColumn.CellTemplate></GridViewColumn><GridViewColumn x:Name="colPrice" x:Uid="GridViewColumn_3" Header="价格" Width="170"><GridViewColumn.CellTemplate><DataTemplate><Grid x:Uid="Grid_4" Height="Auto" Width="Auto"><TextBlock x:Uid="TextBlock_4" HorizontalAlignment="Right" VerticalAlignment="Center"  Margin="0,0,0,0" FontFamily="Arial" FontWeight="Bold" FontSize="15" TextTrimming="WordEllipsis" FontStretch="Normal" ><TextBlock.Text><Binding Path="Price" Converter="{StaticResource myDecimalConverter}"/></TextBlock.Text></TextBlock></Grid></DataTemplate></GridViewColumn.CellTemplate></GridViewColumn></GridView></ListView.View></ListView></StackPanel>
</Window>

运行效果如下,我们可以看到我们的价格已经被格式化:

645f0bc0a23bb4299f83163300ebdfdf.png

我们如果想将数量等于10的背景颜色设置为绿色,又该怎么做的,同样的我们定义一个ColorConverter转换器:

[ValueConversion(typeof(int), typeof(SolidColorBrush))]public class ColorConverter : IValueConverter{public object? Convert(object value, Type targetType, object parameter, CultureInfo culture){if ((int)value == 10)return new SolidColorBrush(Colors.Green); ;return null;}public object? ConvertBack(object value, Type targetType, object parameter, CultureInfo culture){return null;}}

同样我们在XAML中引用一下该对象:

<local:ColorConverter x:Key="myColorConverter"></local:ColorConverter>

在ListView中添加如下样式:

<ListView.ItemContainerStyle><Style x:Uid="Style_2" TargetType="{x:Type ListViewItem}"><Setter Property="Background" Value="{Binding Path=Quantity, Converter={StaticResource myColorConverter}}"></Setter></Style>
</ListView.ItemContainerStyle>

运行效果如下:

71cb4b8ed5a23a06e32291e56b9e9b16.png

从上面例子可以看出我们可以利用IValueConverter接口在数据源和UI之间做一些数据转换,另外微软还提供了一个IMultiValueConverter接口支持多个值转换,我们这里就不说了,感兴趣的小朋友可以研究一下。

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

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

相关文章

使用 Azure CLI 将 IaaS 资源从经典部署模型迁移到 Azure Resource Manager 部署模型

以下步骤演示如何使用 Azure 命令行接口 (CLI) 命令将基础结构即服务 (IaaS) 资源从经典部署模型迁移到 Azure Resource Manager 部署模型。 本文中的操作需要 Azure CLI。 Note 此处描述的所有操作都是幂等的。 如果你遇到功能不受支持或配置错误以外的问题&#xff0c;建议你…

黑苹果不能imessage_如何修复iMessage在iOS 10中不显示消息效果

黑苹果不能imessageiMessage got a huge update in iOS 10, adding things like third-party app integration, rich links, and a number of fun graphical effects for messages. If you’re seeing messages that say something like “(sent with Invisible Ink)” instead…

从技术总监到开源社区运营:过去两年,我都做了点啥?

这是头哥侃码的第267篇原创今天&#xff0c;这是我离开前公司的第 7 天。相信有不少吃瓜群众都很好奇&#xff0c;你这些天都在干啥&#xff1f;是不是蓬莱乐逍遥&#xff0c;过上了那悠闲的神仙日子&#xff1f;还是趁着疫情管控逐渐放开&#xff0c;和家人一起去深山老林里吸…

查看模拟器使用端口_为什么我们仍然使用模拟音频端口?

查看模拟器使用端口When leaks about what the chassis of the iPhone 7 might look like hit headlines earlier this week, technology columnists and industry analysts jumped on the chance to report that Apple’s next device may finally ditch its 3.5mm audio port…

如何更改Windows 10锁定屏幕超时

By default, Windows 10’s lock screen times out and switches off your monitor after one minute. If you’d like it to stick around longer than that–say, if you have background picture you like looking at or you enjoy having Cortana handy–there’s a simple…

ios 开发账号 退出协作_如何在iOS 10中的Notes上进行协作

ios 开发账号 退出协作iOS’ Notes app provides a convenient way to remember the great ideas you come up with and all the things you have to do. The app has evolved over the years, and iOS 10 adds even more features–including collaboration. iOS的Notes应用程…

为什么Android Geeks购买Nexus设备

The Galaxy S III is the highest-selling Android phone, but much of the geeky buzz is around the Nexus 4 – and the Galaxy Nexus before it. Nexus devices are special because they don’t have some of Android’s biggest problems. Galaxy S III是最畅销的Android…

day4----函数-闭包-装饰器

day4----函数-闭包-装饰器 本文档内容&#xff1a; 1 python中三种名称空间和作用域 2 函数的使用 3 闭包 4 装饰器 一 python中三种名称空间和作用域 1.1名称空间&#xff1a; 当程序运行时&#xff0c;代码从上至下依次执行&#xff0c;它会将变量与值得关系存储在一个空间中…

滤波器和均衡器有什么区别_什么是均衡器,它如何工作?

滤波器和均衡器有什么区别It’s in your car, home theater system, phone, and audio player but it doesn’t have an instruction manual. It’s an equalizer, and with a little know-how you can tweak your audio and fall in love with it all over again. 它在您的汽车…

网络视频监控与人脸识别

明天又要去面试了&#xff0c;趁次机会也将以前做的东西总结一下&#xff0c;为以后理解提供方便&#xff0c;也再加深下印象。 网络视频监控与人脸识别主要由三个程序组成&#xff1a;1、视频采集与传输程序&#xff1b;2、接受与显示程序&#xff1b;3、人脸识别程序。下面就…

esxi.主机配置上联端口_为什么现代的电脑机箱仍然具有USB 2.0端口?

esxi.主机配置上联端口With USB 3.0 becoming more prevalent with each passing year now, you may have found yourself wondering why modern computers still have USB 2.0 ports built into them. With that in mind, today’s SuperUser Q&A post has the answers to…

使用命令导入、导出mysql数据

1.导出全部数据库 利用mysqldump的—all-databases参数可以一口气把你数据库root用户下的所有数据库一口气导出到一个sql文件里。然后&#xff0c;重装系统后使用source命令可以再一口气倒回来。 需要确定mysql安装的路径&#xff1a;本机是&#xff1a;C:\Program Files\MySQL…

【原理图操作】原理图更新PCB时未改动元器件布局变动问题?

转载PCB布局、布线完工之后&#xff0c;由于设计功能&#xff0c;发现不完善时, 原理图部分功能需要改动&#xff0c;再改原理图&#xff0c;修改完成后&#xff0c;导入PCB过程中&#xff0c;发现PCB中未改动&#xff08;部分&#xff09;的元器件 布局发生了变化&#xff0c;…

关闭edge任务栏预览_如何在Microsoft Edge中关闭选项卡预览

关闭edge任务栏预览Now that it has extension support, Microsoft Edge is becoming a more and more viable browser. One feature people seem to either love or hate is the pop-up preview you get when you hover over a tab. There’s no built-in setting that lets y…

智能手机丢失 数据安全_丢失智能手机时该怎么办

智能手机丢失 数据安全Phones get stolen or lost everyday. With a plethora of data ripe for identity-theft on it, a lost phone can easily make your blood run cold. Take a deep breath, How-To Geek will talk you through this. 手机每天都会被盗或丢失。 随着大量用…

程序员怎样成为一名架构师?

在今天的技术圈&#xff0c;可能随便遇到一个人递给你一张名片&#xff0c;title 就是某某架构师。架构师多如过江之鲫&#xff0c;也正是眼下业内一个有趣的现象。对于架构师&#xff0c;你有什么看法&#xff1f;什么是架构师&#xff1f;随便打开某招聘网站&#xff1a;系统…

共享没有权限访问权限_如何与家人共享SmartThings访问权限

共享没有权限访问权限If you have multiple people in your household and want them all to have access to SmartThings from their phones, here’s how to share access to SmartThings with anyone you want. 如果您的家庭中有多个人&#xff0c;并且希望他们所有人都可以…

使用jquery+css实现瀑布流布局

虽然可以直接使用css实现瀑布流布局&#xff0c;但显示的方式有点问题&#xff0c;所以这儿就直接使用jquerycss来实现瀑布流布局&#xff0c;最终效果如下&#xff1a; 思路是通过将每个小块的position设置为relative&#xff0c;然后计算出在当前选择的列下应该上移的距离&am…

geek_How-To Geek正在寻找安全作家

geekThink you have the perfect combination of geek knowledge and writing skills? We’re looking for an experienced, security-focused writer to join our team. 认为您将怪胎知识和写作技能完美结合了吗&#xff1f; 我们正在寻找经验丰富&#xff0c;注重安全性的作…

AAC 文件解析及解码流程

OUTLINE&#xff1a; &#xff0a; AAC概述 &#xff0a; AAC规格简述 &#xff0a; AAC特点 &#xff0a; AAC音频文件解析 ——ADIF&#xff06;ADTS格式 ——ADIF&#xff06;ADTS头信息 ——ADIF&#xff06;ADTS数据信息 ——AAC文件处理流程 &#xff0a; AAC解码流程…