2

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.

3 Answers 3

2

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!

Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

The idea is nice, but in this case I´d have to create a new property in my model, using a converter I think is better in this case, because it will only converts when showing in the view. tks.
0

Could do something like this:

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

Regards.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.