【WPF】Converter使用

(1)使用的目的:

实现源数据和目标数据之间进行特定的转化

比如一个User类里有int userLevel字段,1代表管理员,0代表普通用户
那么就需要转换器进行转换来显示文字。

(2)

IValueConverter接口:进行单值转换

IMutilValueConverter接口:进行多值转换  比如一个控件的数据来源自两个变量结合

(3)Convert 方法

将源数据转换为目标数据:

若转换模式为TwoWay,则通过实现IValueConverter接口的ConvertBack方法,将目标数据转换为源数据;

若转换模式为OneWay,则该方法可不做实现,直接返回null。

 (4)

示例1:

/// <summary>
    /// 自定义事件转换
    /// </summary>
    public class TimeConver : IValueConverter
    {
        //当值从绑定源传播给绑定目标时,调用方法Convert
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null)
                return DependencyProperty.UnsetValue;
            DateTime date = (DateTime)value;
            return date.ToString("yyyy-MM-dd");
        }
        //当值从绑定目标传播给绑定源时,调用此方法ConvertBack
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string str = value as string;
            DateTime txtDate;
            if (DateTime.TryParse(str, out txtDate))
            {
                return txtDate;
            }
            return DependencyProperty.UnsetValue;
        }
    }

示例2:

public class SexConverter:IValueConverter
    {
        public object Convert (object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string result = "";
            string sex = (string)value;
            if (sex == "0")
            {
                result = "";
            }
            else if (sex == "1")
            {
                result = "";
            }
            return result;
        }
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); }
    }

xaml绑定:

Converter={StaticResource 转换类名}

 (5)多值绑定

示例:

https://www.cnblogs.com/yaosj/p/11240275.html

 

 

本文引用链接:

1、WPF Binding值转换器ValueConverter使用简介

https://www.cnblogs.com/tianma3798/p/5927470.html

 

2、WPF 中转换器 --Converter使用详解

https://www.cnblogs.com/ramo/p/13476869.html

posted @ 2021-05-22 14:10  不溯流光  阅读(568)  评论(0编辑  收藏  举报