Posted by: Zeeshan Amjad | October 18, 2011

String Converter


We already saw the example of converter that changes the string from lower case to upper case here. And we also the the string encoding into base 64 using MVVM here. Let’s combine these two and create a string convertor that perform both operations and few more using converter parameter.

Our string converter has one parameter that accept 4 different values “Lower”, “Upper”, “Title” and “Base64”. Here is simple implementation of this converter.

Code Snippet
[ValueConversion(typeof(string), typeof(string))]
public class StringConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        string currentString = (string)value;
        string conversion = (string)parameter;            

        if (conversion == "Base64")
        {
            byte[] txtByte = Encoding.Default.GetBytes(currentString);
            string outputString = System.Convert.ToBase64String(txtByte);
            return outputString;
        }
        else if (conversion == "Upper")
        {
            return currentString.ToUpper(culture);
        }
        else if (conversion == "Lower")
        {
            return currentString.ToLower(culture);
        }
        else if (conversion == "Title")
        {
            TextInfo text = culture.TextInfo;
            return text.ToTitleCase(currentString);
        }
                    
        return string.Empty;
    }

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

 

Here is a usage of this converter.

Code Snippet
<TextBlock Grid.Column="1" Grid.Row="1" Margin="5" VerticalAlignment="Center"
           Text="{Binding ElementName=text, Path=Text,
           Converter={StaticResource objStringConverter}, ConverterParameter='Upper',
           NotifyOnSourceUpdated=True}"/>

 

Here is complete XAML code of the program.

Code Snippet
<Window x:Class="WpfStringConverter.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml&quot;
        xmlns:local="clr-namespace:WpfStringConverter"
        Title="String Converter" Height="400" Width="600">
    <Window.Resources>
        <local:StringConverter x:Key="objStringConverter"/>
    </Window.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition Width="2*"/>
        </Grid.ColumnDefinitions>
        <TextBlock Grid.Column="0" Grid.Row="0" Margin="5" VerticalAlignment="Center">Enter Text</TextBlock>
        <TextBox Grid.Column="1" Grid.Row="0" Name="text" VerticalAlignment="Center" Margin="5"/>
        <TextBlock Grid.Column="0" Grid.Row="1" Margin="5" VerticalAlignment="Center">Upper String</TextBlock>
        <TextBlock Grid.Column="1" Grid.Row="1" Margin="5" VerticalAlignment="Center"
                   Text="{Binding ElementName=text, Path=Text,
                   Converter={StaticResource objStringConverter}, ConverterParameter='Upper',
                   NotifyOnSourceUpdated=True}"/>
        <TextBlock Grid.Column="0" Grid.Row="2" Margin="5" VerticalAlignment="Center">Lower String</TextBlock>
        <TextBlock Grid.Column="1" Grid.Row="2" Margin="5" VerticalAlignment="Center"
                   Text="{Binding ElementName=text, Path=Text,
                   Converter={StaticResource objStringConverter}, ConverterParameter='Lower',
                   NotifyOnSourceUpdated=True}"/>
        <TextBlock Grid.Column="0" Grid.Row="3" Margin="5" VerticalAlignment="Center">Title String</TextBlock>
        <TextBlock Grid.Column="1" Grid.Row="3" Margin="5" VerticalAlignment="Center"
                   Text="{Binding ElementName=text, Path=Text,  
                   Converter={StaticResource objStringConverter}, ConverterParameter='Title',
                   NotifyOnSourceUpdated=True}"/>
        <TextBlock Grid.Column="0" Grid.Row="4" Margin="5" VerticalAlignment="Center">Base64 encoding String</TextBlock>
        <TextBlock Grid.Column="1" Grid.Row="4" Margin="5" VerticalAlignment="Center"
                   Text="{Binding ElementName=text, Path=Text,
                   Converter={StaticResource objStringConverter}, ConverterParameter='Base64',
                   NotifyOnSourceUpdated=True}"/>
    </Grid>
</Window>

 

And here is a complete C# code of the program.

Code Snippet
using System;
using System.Globalization;
using System.Text;
using System.Windows;
using System.Windows.Data;

namespace WpfStringConverter
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }

    [ValueConversion(typeof(string), typeof(string))]
    public class StringConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string currentString = (string)value;
            string conversion = (string)parameter;            

            if (conversion == "Base64")
            {
                byte[] txtByte = Encoding.Default.GetBytes(currentString);
                string outputString = System.Convert.ToBase64String(txtByte);
                return outputString;
            }
            else if (conversion == "Upper")
            {
                return currentString.ToUpper(culture);
            }
            else if (conversion == "Lower")
            {
                return currentString.ToLower(culture);
            }
            else if (conversion == "Title")
            {
                TextInfo text = culture.TextInfo;
                return text.ToTitleCase(currentString);
            }
                        
            return string.Empty;
        }

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

 

This is an output of the program.

StringConverterOutput

Advertisements

Responses

  1. […] example of string convert where we convert string to base64, title case, lower case and upper case here. Lets make a attached dependency property to do the same thing. First thing we do is to change the […]

  2. […] Converter Revisited We saw one example of string convertor here. We also implemented this in the form of Attached Dependency property here. Now we are going to […]


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: