Search This Blog

Monday, May 19, 2014

WPF Converter Example

WPF > Data > Converters

Converters changes data from one type to another and apply custom logic to binding.
Implementation : create a class that implements the IvalueConverter.

Example:


XAML:

<Window x:Class="WpfApplication2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication2"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <local:YesNoConverter x:Key="YesNoConverter" />
    </Window.Resources>
    <StackPanel Margin="5">
        <CheckBox x:Name="chk" IsChecked="{Binding ElementName=txtYesNo, Path=Text, Converter={StaticResource YesNoConverter}}" Content="Yes/No" />
        <TextBox Name="txtYesNo" />
    </StackPanel>
</Window>

C# Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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.Navigation;
using System.Windows.Shapes;

namespace WpfApplication2
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    ///
    public class YesNoConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            switch (value.ToString())
            {
                case "Yes":
                    return true;
                case "No":
                    return false;
            }
            return false;
        }
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value is bool)
            {
                if ((bool)value == true)
                    return "Yes";
                else
                    return "No";
            }
            return "No";
        }
    }
    public partial class MainWindow : Window
    {
     
        public MainWindow()
        {
            InitializeComponent();
        }
    }
}