WPF之转换器Converter (IValueConverter)

WPF之转换器Converter (IValueConverter)


使用步骤

例子:OK文字转绿色,NG转红色

1.定义继承IValueConverter

 public class String2BrushConverter : IValueConverter
 {
     public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
     {
         string res = (string)value;
         if (res == "OK")
             return Brushes.DarkGreen;
         else if (res == "NG")
             return Brushes.Red;
         else
             return Brushes.DarkGreen;
     }

     public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
     {
         throw new NotImplementedException();
     }
 }

2.放到资源中

   <Window.Resources>
       <cv:String2BrushConverter x:Key="String2BrushConvert"/>
   </Window.Resources>

3.在控件中进行使用

在这里插入图片描述

  <Rectangle Margin="0" Stroke="White" StrokeThickness="1" Width="70" Height="70" 
       RadiusX="8" RadiusY="8" HorizontalAlignment="Center" Fill="{Binding Result, Converter={StaticResource String2BrushConvert}}"/>

转换器可以将数据从一种类型更改为另一种类型

参数类型含义
valueobject绑定源生成的值
targetTypeType绑定目标属性的类型
parameterobject要使用的转换器参数
cultureCultureInfo要用在转换器中的区域性
   public class BoolValueConverter : IValueConverter
   {
       public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
       {
           bool valid = (bool)value;
           string val = (string)parameter;
           if (valid)
           {
               if (val == "Transparent")
                   return Brushes.Transparent;
               else
                   return Brushes.Green;
           }
           return Brushes.Red;
       }

       public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
       {
           throw new NotImplementedException();
       }
   }

在WPF(Windows Presentation Foundation)中,IValueConverter 接口是一个非常重要的接口,它允许你在绑定(Binding)过程中将源值(Source Value)转换为目标值(Target Value),或者将目标值转换回源值(尽管后者在大多数情况下不是必需的)。这在你需要将数据以不同的格式显示给用户,或者需要将用户输入的数据转换为后端逻辑可以理解的格式时非常有用。

实现 IValueConverter 接口

首先,你需要创建一个实现了 IValueConverter 接口的类。这个接口定义了两个方法:ConvertConvertBack

在数据绑定(Data Binding)的上下文中,我们经常使用继承 IValueConverter 接口的类,用于在源值和目标值之间进行转换。该接口定义了两个方法:Convert 和 ConvertBack,这两个方法分别用于从源值到目标值的转换和从目标值回到源值的转换(如果绑定支持双向绑定)。

在这里插入图片描述

using System;
using System.Globalization;
using System.Windows.Data;

public class BoolToVisibilityConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (targetType != typeof(System.Windows.Visibility))
            throw new InvalidOperationException("The target must be a Visibility type");

        bool isVisible = (bool)value;
        return isVisible ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
    }

    public object ConvertBack(object value, Type sourceType, object parameter, CultureInfo culture)
    {
        if (sourceType != typeof(System.Windows.Visibility))
            throw new InvalidOperationException("The source must be a Visibility type");

        System.Windows.Visibility visibility = (System.Windows.Visibility)value;
        return visibility == System.Windows.Visibility.Visible;
    }
}

在XAML中使用转换器

在XAML中使用这个转换器之前,你需要将它作为一个资源添加到你的XAML文件中。这通常是在窗口(Window)或用户控件(UserControl)的 <Window.Resources><UserControl.Resources> 部分完成的。

<Window x:Class="YourNamespace.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:YourNamespace"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <local:BoolToVisibilityConverter x:Key="boolToVisibilityConverter"/>
    </Window.Resources>
    <!-- 窗口内容 -->
</Window>

在绑定中使用转换器

现在,你可以在绑定中使用这个转换器了。假设你有一个布尔类型的属性,你想根据这个属性的值来控制某个控件的可见性。

<CheckBox Content="Show Details" IsChecked="{Binding ShowDetails}"/>
<TextBlock Text="这里是详细信息..." Visibility="{Binding ShowDetails, Converter={StaticResource boolToVisibilityConverter}}"/>

在这个例子中,TextBlockVisibility 属性绑定到了 ShowDetails 属性上,并且使用了 boolToVisibilityConverter 转换器来将布尔值转换为 Visibility 枚举值。当 ShowDetailstrue 时,TextBlock 可见;为 false 时,TextBlock 不可见。

注意事项

  • 转换器可以非常强大,但过度使用可能会使XAML变得难以理解和维护。
  • 转换器可以处理复杂的逻辑,但请确保它们保持简单和直接,以避免引入难以调试的错误。
  • 转换器可以接收参数,这允许你创建更通用的转换器,这些转换器可以根据需要调整其行为。在 ConvertConvertBack 方法的 parameter 参数中接收这些参数。

实例:

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值