ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

WPF转换器 IValueConverter

2021-11-30 11:04:29  阅读:162  来源: 互联网

标签:绑定 IValueConverter System object value using 转换器 WPF


转换器 IValueConverter 接口

定义:
提供将自定义逻辑应用于绑定的方法。

如果要将值转换器与绑定相关联,请创建一个实现接口的类继承IValueConverter,然后实现 Convert 和 ConvertBack 方法。 转换器可将数据从一种类型更改为另一种类型,根据区域性信息转换数据,或修改演示的其他方面。
值转换器识别区域性。 Convert和 ConvertBack 方法都有一个 culture 指示区域性信息的参数。 如果区域性信息与转换无关,则可在自定义转换器中忽略该参数。
Convert和 ConvertBack 方法也有一个名为parameter的参数, parameter 以便你可以使用具有不同参数的转换器的同一实例。 例如,你可以编写一个格式转换器,该转换器根据你使用的输入参数生成不同的数据格式。 您可以使用 ConverterParameter Binding 类的来将参数作为参数传递到 Convert 和 ConvertBack 方法。

方法:
Convert(Object, Type, Object, CultureInfo) 转换值。
ConvertBack(Object, Type, Object, CultureInfo) 转换值。

#region 程序集 PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
// C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\PresentationFramework.dll
#endregion

using System.Globalization;

namespace System.Windows.Data
{
    //
    // 摘要:
    //     提供将自定义逻辑应用于绑定的方法。
    public interface IValueConverter
    {
        //
        // 摘要:
        //     转换值。
        //
        // 参数:
        //   value:
        //     绑定源生成的值。
        //
        //   targetType:
        //     绑定目标属性的类型。
        //
        //   parameter:
        //     要使用的转换器参数。
        //
        //   culture:
        //     要用在转换器中的区域性。
        //
        // 返回结果:
        //     转换后的值。 如果该方法返回 null,则使用有效的 null 值。
        object Convert(object value, Type targetType, object parameter, CultureInfo culture);
        //
        // 摘要:
        //     转换值。
        //
        // 参数:
        //   value:
        //     绑定目标生成的值。
        //
        //   targetType:
        //     要转换为的类型。
        //
        //   parameter:
        //     要使用的转换器参数。
        //
        //   culture:
        //     要用在转换器中的区域性。
        //
        // 返回结果:
        //     转换后的值。 如果该方法返回 null,则使用有效的 null 值。
        object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture);
    }
}

继承IValueConverter接口:

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Windows.Data;

namespace ConverterDemo.Converter
{
    public class DateTimeConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }

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

Convert:

参数
value Object
绑定源生成的值。
targetType Type
绑定目标属性的类型。
parameter Object
要使用的转换器参数。
culture CultureInfo
要用在转换器中的区域性。

返回
Object
转换后的值。 如果该方法返回 null,则使用有效的 null 值。

注解
数据绑定引擎在将值从绑定源传播到绑定目标时会调用此方法。
数据绑定引擎不会捕获由用户提供的转换器引发的异常。 方法所引发的任何异常 Convert ,或方法调用的方法所引发的任何未捕获异常 Convert 均被视为运行时错误。 通过返回来处理预期问题 DependencyProperty.UnsetValue 。
的返回值 DependencyProperty.UnsetValue 指示转换器没有生成值,并且绑定将使用 FallbackValue (如果可用)或默认值。
返回值 Binding.DoNothing 指示绑定不传输值或使用 FallbackValue 或默认值。

示例:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;

namespace ConverterDemo
{
    public class ConverterViewModel : INotifyPropertyChanged
    {
        #region INotifyPropertyChanged
        public event PropertyChangedEventHandler PropertyChanged;

        public virtual void OnPropertyChanged(string propertyName)
        {
            var propertyChanged = PropertyChanged;

            if (propertyChanged != null)
            {
                propertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        #endregion

        private DateTime _testDate;

        /// <summary>
        /// 测试数据
        /// </summary>
        public DateTime TestDate
        {
            get { return _testDate; }

            set
            {
                _testDate = value;
                OnPropertyChanged("TestDate");
            }
        }

    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace ConverterDemo
{
    /// <summary>
    /// ConverterPage.xaml 的交互逻辑
    /// </summary>
    public partial class ConverterPage : Window
    {
        ConverterViewModel viewModel;
        public ConverterPage()
        {
            InitializeComponent();

            viewModel = new ConverterViewModel();
            this.DataContext = viewModel;
        }
    }
}
<Window x:Class="ConverterDemo.ConverterPage"
        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:ConverterDemo"
        mc:Ignorable="d"
        xmlns:converter ="clr-namespace:ConverterDemo.Converter"
        Title="ConverterPage" Height="450" Width="800">
    <Window.Resources>
        <converter:DateTimeConverter x:Key="DateTimeConverter"/>
    </Window.Resources>
    <Grid>
        <Label Content="使用转换器" HorizontalAlignment="Left" Margin="118,129,0,0" VerticalAlignment="Top"/>
        <Label Content="未使用转换器" HorizontalAlignment="Left" Margin="118,171,0,0" VerticalAlignment="Top"/>
        <TextBlock HorizontalAlignment="Left" Margin="279,134,0,0" TextWrapping="Wrap" 
                   Text="{Binding TestDate,Converter={StaticResource DateTimeConverter}}" VerticalAlignment="Top"/>
        <TextBlock HorizontalAlignment="Left" Margin="279,176,0,0" TextWrapping="Wrap" 
                   Text="{Binding TestDate}" VerticalAlignment="Top"/>
    </Grid>
</Window>
	public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value != null && DateTime.TryParse(value.ToString(), out DateTime result))
            {
                return result.ToString("yyyy-MM-dd");
            }

            return value;
        }

ConvertBack:

参数
value Object
绑定目标生成的值。
targetType Type
要转换为的类型。
parameter Object
要使用的转换器参数。
culture CultureInfo
要用在转换器中的区域性。

返回
Object
转换后的值。 如果该方法返回 null,则使用有效的 null 值。

注解
数据绑定引擎在将值从绑定目标传播到绑定源时调用此方法。
此方法的实现必须是方法的反向实现 Convert 。
数据绑定引擎不会捕获由用户提供的转换器引发的异常。 方法所引发的任何异常 ConvertBack ,或方法调用的方法所引发的任何未捕获异常 ConvertBack 均被视为运行时错误。 通过返回来处理预期 DependencyProperty 问题。 UnsetValue
的返回值 DependencyProperty.UnsetValue 指示转换器没有生成值,并且绑定将使用 FallbackValue (如果可用)或默认值。
返回值 Binding.DoNothing 指示绑定不传输值或使用 FallbackValue 或默认值。

代码:


标签:绑定,IValueConverter,System,object,value,using,转换器,WPF
来源: https://www.cnblogs.com/Simple-Sun/p/15623272.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有