WPF converter IValueConverter

converter IValueConverter interface

definition:
Provides methods for applying custom logic to bindings.

If you want to associate a value converter with a binding, create a class that implements the interface, inherits IValueConverter, and then implements the Convert and ConvertBack methods. The converter can change data from one type to another, Convert data based on culture information, or modify other aspects of the presentation.
The value converter identifies the culture. Both the Convert and ConvertBack methods have a culture parameter indicating culture information. If the culture information is not related to the conversion, you can ignore this parameter in the custom converter.
The Convert and ConvertBack methods also have a parameter called parameter so that you can use the same instance of the converter with different parameters. For example, you can write a format converter that generates different data formats according to the input parameters you use. You can use the of the ConverterParameter Binding class to pass parameters as parameters to the Convert and ConvertBack methods.

method:
Convert(Object, Type, Object, CultureInfo) converts values.
ConvertBack(Object, Type, Object, CultureInfo) converts values.

#region assembly 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
{
    //
    // Summary:
    //     Provides methods for applying custom logic to bindings.
    public interface IValueConverter
    {
        //
        // Summary:
        //     Convert values.
        //
        // Parameters:
        //   value:
        //     The value generated by the binding source.
        //
        //   targetType:
        //     The type of the bound target property.
        //
        //   parameter:
        //     The converter parameters to use.
        //
        //   culture:
        //     The culture to use in the converter.
        //
        // Return result:
        //     Converted value. If the method returns null, a valid null value is used.
        object Convert(object value, Type targetType, object parameter, CultureInfo culture);
        //
        // Summary:
        //     Convert values.
        //
        // Parameters:
        //   value:
        //     The value generated by the binding target.
        //
        //   targetType:
        //     Type to convert to.
        //
        //   parameter:
        //     The converter parameters to use.
        //
        //   culture:
        //     The culture to use in the converter.
        //
        // Return result:
        //     Converted value. If the method returns null, a valid null value is used.
        object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture);
    }
}

Inherit IValueConverter interface:

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:

parameter
value Object
The value generated by the binding source.
targetType Type
The type of the bound target property.
parameter Object
The converter parameters to use.
culture CultureInfo
The culture to use in the converter.

return
Object
Converted value. If the method returns null, a valid null value is used.

annotation
The data binding engine calls this method when it propagates a value from the binding source to the binding target.
The data binding engine does not catch exceptions thrown by user supplied converters. Any exception Convert thrown by a method or any uncapped exception Convert thrown by a method called by a method is considered a runtime error. Handle the expected problem DependencyProperty.UnsetValue by returning.
The return value of DependencyProperty.UnsetValue indicates that the converter does not generate a value and that the binding will use FallbackValue (if available) or the default value.
The return value Binding.DoNothing indicates that the binding does not transmit a value or uses a FallbackValue or default value.

Example:

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>
        ///Test data
        /// </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>
    ///Interactive logic of 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="Use converter" HorizontalAlignment="Left" Margin="118,129,0,0" VerticalAlignment="Top"/>
        <Label Content="Converter not used" 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:

parameter
value Object
The value generated by the binding target.
targetType Type
Type to convert to.
parameter Object
The converter parameters to use.
culture CultureInfo
The culture to use in the converter.

return
Object
Converted value. If the method returns null, a valid null value is used.

annotation
The data binding engine calls this method when it propagates a value from the binding target to the binding source.
The implementation of this method must be the reverse implementation of the method Convert.
The data binding engine does not catch exceptions thrown by user supplied converters. Any exception ConvertBack thrown by a method, or any uncapped exception ConvertBack thrown by a method called by a method, is considered a runtime error. Handle the expected DependencyProperty problem by returning. UnsetValue
The return value of DependencyProperty.UnsetValue indicates that the converter does not generate a value and that the binding will use FallbackValue (if available) or the default value.
The return value Binding.DoNothing indicates that the binding does not transmit a value or uses a FallbackValue or default value.

code:

Tags: WPF

Posted on Mon, 29 Nov 2021 22:12:56 -0500 by mariom