will
will

Reputation: 1012

WPF StringFormat formatting string values

Is it possible to format a string using StringFormat...

for example.. my model:

 public class MyModel
 {
      public string Code { get; set; } 
 }

Possible values for Code are: '00000101001', '00000201001', etc...

When binding, i´d like to show: For '00000101001' -> '000001-01' (Ignore last 3 characters) For '00000201001' -> '000002-01' (Ignore last 3 characters)

If its possible using stringformat to achieve this, would be nice instead have to implement by my own.

Upvotes: 2

Views: 1089

Answers (3)

Gayot Fow
Gayot Fow

Reputation: 8792

Your question asked about BINDING a string in WPF (without altering the internal content of the string), and among the preferred strategies for solving this is to use a converter, here's an example that does what you're looking for (display the first 10 characters only)...

public class CodeConverter : MarkupExtension, IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, 
                   System.Globalization.CultureInfo culture)
    {
        try
        {
            string result = value.ToString();
            if (result.Length > 10)
            {
                // code in your exact requirements here...
                return result.Substring(0, 10);
            }
            return result;
        }
        catch{}
        return value;
    }
    public object ConvertBack(object value, Type targetType, object parameter,      
                     System.Globalization.CultureInfo culture)
    {
        return null;
    }
    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return this;
    }
}

In your Xaml, simply specify this class in your binding...

{Binding Code, Converter={StaticResource CodeConverter}

And you're good to go!

Upvotes: 2

Could do something like this:

return (Int64.Parse("00000101001") / 1000).ToString("000000-00");

Regards.

Upvotes: 0

dsfgsho
dsfgsho

Reputation: 2769

Just use a conversion function. E.g:

public static string Convert(string raw)
{
    return raw.Substring(0,6)+"-"+raw.Substring(6,2);
}

Console.WriteLine (Convert("00000201001"));

//output= 000002-01

Upvotes: 0

Related Questions