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.pswp.cn/news/280223.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/280223.shtml
英文地址,請注明出處:http://en.pswp.cn/news/280223.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

JVM學習記錄-類加載的過程

類的整個生命周期的7個階段是&#xff1a;加載&#xff08;Loading&#xff09;、驗證(Verification)、準備(Preparation)、解析(Resolution)、初始化(Initialization)、使用(Using)、卸載(Unloading)。 類加載的全過程主要包括&#xff1a;加載、驗證、準備、解析、初始化這5個…

使用 Azure CLI 將 IaaS 資源從經典部署模型遷移到 Azure Resource Manager 部署模型

以下步驟演示如何使用 Azure 命令行接口 (CLI) 命令將基礎結構即服務 (IaaS) 資源從經典部署模型遷移到 Azure Resource Manager 部署模型。 本文中的操作需要 Azure CLI。 Note 此處描述的所有操作都是冪等的。 如果你遇到功能不受支持或配置錯誤以外的問題&#xff0c;建議你…

c++的進制轉換函數

https://blog.csdn.net/u010003835/article/details/47665847https://blog.csdn.net/vir_lee/article/details/80645066strtol函數&#xff1a;用于由十進制轉化到2~36的其他進制。函數原型為&#xff1a;long int strtol(const char *nptr,char **endptr,int base); 還應該注意…

黑蘋果不能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…

MyBatisPlus怎么忽略映射字段

TableField(exist false)&#xff1a;表示該屬性不為數據庫表字段&#xff0c;但又是必須使用的。 TableField(exist true)&#xff1a;表示該屬性為數據庫表字段。 Mybatis-Plus 插件有這個功能&#xff0c;可以看一下 TableName&#xff1a;數據庫表相關 TableId&#xff1…

從技術總監到開源社區運營:過去兩年,我都做了點啥?

這是頭哥侃碼的第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…

ServletContextListener在Springboot中的使用

ServletContextListener是servlet容器中的一個API接口, 它用來監聽ServletContext的生命周期&#xff0c;也就是相當于用來監聽Web應用的生命周期。今天我們就來說說如何在Springboot 1.5.2這個輕量型框架中如何使用它。 其實配置ServletContextListener與其它Filter, Listener…

《ASP.NET Core 6框架揭秘》實例演示[34]:緩存整個響應內容

我們利用ASP.NET開發的大部分API都是為了對外提供資源&#xff0c;對于不易變化的資源內容&#xff0c;針對某個維度對其實施緩存可以很好地提供應用的性能。《內存緩存與分布式緩存的使用》介紹的兩種緩存框架&#xff08;本地內存緩存和分布式緩存&#xff09;為我們提供了簡…

常見端口介紹

Win常用端口 TCP端口&#xff08;靜態端口&#xff09;TCP 0 ReservedTCP 1TCP Port Service MultiplexerTCP 2DeathTCP 5Remote Job Entry,yoyoTCP 7EchoTCP 11SkunTCP 12BomberTCP 16SkunTCP 17SkunTCP 18消息傳輸協議&#xff0c;skunTCP 19SkunTCP 20FTP Data,Amanda TCP 2…

如何更改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應用程…

poj 1182

食物鏈Time Limit: 1000MS Memory Limit: 10000KTotal Submissions: 86494 Accepted: 25887Description 動物王國中有三類動物A,B,C&#xff0c;這三類動物的食物鏈構成了有趣的環形。A吃B&#xff0c; B吃C&#xff0c;C吃A。 現有N個動物&#xff0c;以1&#xff0d;N編號。每…

條款6:若不想使用編譯器自動生成的函數,就該明確拒絕

如果自己定義的類中并不需要copy assignment操作符或者copy構造函數&#xff0c;為了避免編譯器自動生成因為編譯器自動生成的沒什么用&#xff0c;一般是按照順序進行賦值或者拷貝&#xff0c;對于有對象內含有指針的話可能會出現一些問題可以在private中聲明&#xff08;并不…

為什么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…

你的知識死角不能否定你的技術能力

有些事情你不知道&#xff0c;但你一定能解決。 有些人通過我賬號資料里的微信加我&#xff0c;然后問我一些所謂“怎么辦”的問題&#xff0c;不是我不告訴你&#xff0c;而是我確實不知道。我確實有很高的title&#xff0c;也確實有很多的技術積累&#xff0c;但我并沒有達到…

算法練習(十二)

The Suspects Description 嚴重急性呼吸系統綜合癥( SARS), 一種原因不明的非典型性肺炎,從2003年3月中旬開始被認為是全球威脅。為了減少傳播給別人的機會, 最好的策略是隔離可能的患者。 在Not-Spreading-Your-Sickness大學( NSYSU), 有許多學生團體。同一組的學生經常彼此相…

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、人臉識別程序。下面就…