How to format text (not numbers nor dates) in DataBinding StringFormat?

I have a text code, let say "NT0040E53", which must be shown as "NT.0040.E5-3". I know that for numeric data we can do...

"{Binding Path=MyCode, StringFormat={0:#,#.0}}" 

Then, for text I would expect to write something like...

"{Binding Path=MyCode, StringFormat={0:@@.@@@@.@@-@}}" 

But that does not exist, as far as I've investigated. So, how text can be formatted with intercalated characters with databinding StringFormat?

Upvotes: 0

Views: 50

Answers (1)

Stígandr
Stígandr

Reputation: 2902

Hi you need to use a converter for this as stated by Rohit Vats.

Xaml:

<Window....>
    <Window.Resources>
        <local:TestConverter x:Key="TestConverter"/>
    <Window.Resources>
    ....
    <TextBlock Text="{Binding MyCode, Converter={StaticResource TestConverter}, ConverterParameter='0:#,#.0'}"></TextBlock>

TestConverter.cs

public class TestConverter : IValueConverter
{
    // converts your bound data value = binding, parameter = ConverterParameter
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        String str = value != null ? value.ToString() : String.Empty;
        String param = parameter != null ? parameter.ToString() : null;            
        return !String.IsNullOrEmpty(str) ? WhatEverYouWantToDoHere(param) : String.Empty;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        // Required if you need to convert back.... 
        throw new NotImplementedException();
    }
}

Converters kinda rocks in WPF/SL :)

Hope it helps!

Cheers,

Stian

Upvotes: 3

Related Questions