Posted by: Zeeshan Amjad | November 24, 2011

String 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 implement the same thing with markup extension. We are going to use the same technique to use value converter in markup extension here. We are gong to do the same, i.e. create a class that is child class of MarkupExtension class and implement IValueConverter interface.

Here is our class.

Code Snippet
    public class StringConversionExtension : MarkupExtension, IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string currentString = (string)value;
            string conversion = (string)parameter;

            if (conversion.ToUpper() == "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, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            return this;
        }
    }

 

We are using Converter parameter to pass different values of the parameter to convert string into different format. Here is the usage of this markup extension.

Code Snippet
<GridViewColumn Header="Title" Width="Auto">
    <GridViewColumn.CellTemplate>
        <DataTemplate>
            <TextBlock Margin="2" Text="{Binding Path=., Converter={StaticResource stringConvertor}, ConverterParameter='Title'}" />
        </DataTemplate>
    </GridViewColumn.CellTemplate>
</GridViewColumn>

 

Here is a complete code of the program.

Code Snippet
using System;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Text;
using System.Windows;
using System.Windows.Data;
using System.Windows.Markup;

namespace WpfStringConversion
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private ObservableCollection<string> states = new ObservableCollection<string>();

        public MainWindow()
        {
            InitializeComponent();

            states.Add("maryland");
            states.Add("virginia");
            states.Add("washington");
            states.Add("california");

            DataContext = states;
        }
    }

    public class StringConversionExtension : MarkupExtension, IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string currentString = (string)value;
            string conversion = (string)parameter;

            if (conversion.ToUpper() == "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, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            return this;
        }
    }
}

And here is a XAML code of our program.

Code Snippet
<Window x:Class="WpfStringConversion.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:WpfStringConversion"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <local:StringConversionExtension x:Key="stringConvertor"/>
    </Window.Resources>
    <Grid>
        <ListView ItemsSource="{Binding}">
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="Title" Width="Auto">
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <TextBlock Margin="2" Text="{Binding Path=., Converter={StaticResource stringConvertor}, ConverterParameter='Title'}" />
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>
                    <GridViewColumn Header="Upper" Width="Auto">
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <TextBlock Margin="2" Text="{Binding Path=., Converter={StaticResource stringConvertor}, ConverterParameter='Upper' }" />
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>
                    <GridViewColumn Header="Lower" Width="Auto">
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <TextBlock Margin="2" Text="{Binding Path=., Converter={StaticResource stringConvertor}, ConverterParameter='Lower' }" />
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>
                    <GridViewColumn Header="Base64" Width="Auto">
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <TextBlock Margin="2" Text="{Binding Path=., Converter={StaticResource stringConvertor}, ConverterParameter='Base64' }" />
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>
                </GridView>
            </ListView.View>
        </ListView>
    </Grid>
</Window>

 

Here is an output of the program.

AttachedPropertyOutput2

Advertisements

Responses

  1. […] But like lots of other WPF thing, here we can do it in more than one way. We can create a markup extension which implement the IMultiValueConverter interface. We already saw few examples of markup extension which implement IValueConverter here and here. […]


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: