WickedFAN
WickedFAN

Reputation: 65

Adding a word in the middle of a value by using StringFormat

I met this problem today , by using binding ; I could binding a number of values in a xaml file , the value looks like 58000.1234 , 58000.2234 , 58431.100 etc. I want to add a word in the middle of this value , which it could turn out to be 58x000.1 ,58x000.2, 58x431.1

I found StringFormat could be a good method for dealing my problem , so I somehow tried this following code ,

<TextBlock Text="{Binding Distance, RelativeSource={RelativeSource TemplatedParent}, StringFormat='{}{0:0.#}'}" />

it manage the point value problem , but i still don't know how to add the x in the middle of my values .

StringFormat='distance {0:0.#} m'

This code can add words before and after value .

Upvotes: 2

Views: 368

Answers (3)

Gope
Gope

Reputation: 1778

You cannot divide the value. You will have to use an ValueConverter in the Binding.

 public class WordSplitConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string input = value.ToString();
            // you can parameterize the split position via the ConverterParameter
            string left = input.Substring(0,2);
            string right= input.Substring(2,input.Length-3);
            return string.Format("{0}X{1}",left ,right);
        }

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

Usage:

<local:WordSplitConverter x:Key="wordSplitConverter" />

<TextBlock Text="{Binding Distance, RelativeSource={RelativeSource TemplatedParent},Converter={StaticResource wordSplitConverter}" />

Please add the approriate error handling... ;)

Upvotes: 0

Andrei  Zubov
Andrei Zubov

Reputation: 578

Try using string format like this:

<TextBlock Text="{Binding Number, StringFormat='{}##x###.#'}" />

That should do the trick.

Upvotes: 1

Thinking Sites
Thinking Sites

Reputation: 3542

Pretty simple, just add it to the format:

string.Format("{0:000 hello 000.00}", 123456);
//123 hello 456.00

Bear in mind that the zeros here are placeholders for values from right to left. This is useful for formatting phone numbers too.

string.Format("{0:(000) 000-0000}", 8885551212);
//(888) 555-1212

Lastly, you can also use the hash (#) mark for a placeholder as well.

Here's the full documentation: http://msdn.microsoft.com/en-us/library/0c899ak8(v=vs.110).aspx

Upvotes: 3

Related Questions