For those that have tried every answer to this question and are still scratching their heads as to why none of them work for you, you might have ran into a form of the issue I ran into.
My TextBlock.Text
property was inside of a ToolTipService.ToolTip
element and it was databound to a property of an object whose data was being pulled from a SQL stored procedure. Now the data from this particular property within the stored procedure was being pulled from a SQL function.
Since nothing had worked for me, I gave up my search and created the converter class below:
public class NewLineConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var s = string.Empty;
if (value.IsNotNull())
{
s = value.ToString();
if (s.Contains("\\r\\n"))
s = s.Replace("\\r\\n", Environment.NewLine);
if (s.Contains("\\n"))
s = s.Replace("\\n", Environment.NewLine);
if (s.Contains("

"))
s = s.Replace("

", Environment.NewLine);
if (s.Contains("
"))
s = s.Replace("
", Environment.NewLine);
if (s.Contains("
"))
s = s.Replace("
", Environment.NewLine);
if (s.Contains(" "))
s = s.Replace(" ", Environment.NewLine);
if (s.Contains(" "))
s = s.Replace(" ", Environment.NewLine);
if (s.Contains(" "))
s = s.Replace(" ", Environment.NewLine);
if (s.Contains("<br />"))
s = s.Replace("<br />", Environment.NewLine);
if (s.Contains("<LineBreak />"))
s = s.Replace("<LineBreak />", Environment.NewLine);
}
return s;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
I ended up having to use the Enivornment.NewLine
method from @dparker's answer. I instructed the converter to look for any possible textual representation of a newline and replace it with Environment.NewLine
.
This worked!
However, I was still perplexed as to why none of the other methods worked with databound properties.
I left a comment on @BobKing's accepted answer:
@BobKing - This doesn't seem to work in the ToolTipService.ToolTip when binding to a field that has the line feeds embedded from a SQL sproc.
He replied with:
@CodeMaverick If you're binding to text with the new lines embedded, they should probably be real char 10 values (or 13's) and not the XML sentinels. This is only if you want to write literal new lines in XAML files.
A light bulb went off!
I went into my SQL function, replaced my textual representations of newlines with ...
CHAR( 13 ) + CHAR( 10 )
... removed the converter from my TextBlock.Text
binding, and just like that ... it worked!