22

This works fine, and correctly inserts non-breaking spaces into the string:

<TextBlock Text="Non&#160;Breaking&#160;Text&#160;Here"></TextBlock>

But what I really need is to replace spaces with non-breaking spaces during data binding. So I wrote a simple value converter that replaces spaces with "&#160;". It does indeed replace spaces with "&#160;" but "&#160;" is displayed literally instead of showing as a non-breaking space. This is my converter:

public class SpaceToNbspConverter : IValueConverter
{
    #region IValueConverter Members

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return value.ToString().Replace(" ", "&#160;");
    }

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

    #endregion
}

Does anybody know why it works in XAML, but not in code?

Kit
  • 20,354
  • 4
  • 60
  • 103
Henrik Söderlund
  • 4,286
  • 3
  • 26
  • 26
  • 2
    This is great, I didn't know how to do non-breaking space before. Thanks for the question! It answered my own question! – cplotts Apr 21 '11 at 14:46

3 Answers3

25

In code the syntax for escaping Unicode chars is different than in XAML:

XAML: &#160;
C#:   \x00A0

So this should have worked in code:

return value.ToString().Replace(" ", "\xA0");
JCH2k
  • 3,361
  • 32
  • 25
18

Have you tried return value.ToString().Replace(' ', System.Convert.ToChar(160)); ?

bitbonk
  • 48,890
  • 37
  • 186
  • 278
4

The reason Char is working and string is not - is that the string is escaped when rendered.

Goblin
  • 7,970
  • 3
  • 36
  • 40