WPF-19 IValueConverter接口

Posted dotNET跨平台

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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");
            else
                return 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>

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

我们如果想将数量等于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>

运行效果如下:

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

以上是关于WPF-19 IValueConverter接口的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 IValueConverter 接口在 Windows 商店应用程序中制作货币转换器?

WPF 格式化输出- IValueConverter接口的使用 datagrid列中的值转换显示

Xamarin.Forms:为啥 IValueConverter 的过程不会永远打乒乓球?

Convert和RelativeSource

如何传递 IValueConverter 参数?

ResourceDictionary 中的 IValueConverter