Line breaks are being ignored when binding to a string StaticResource - silverlight

We're developing a Windows Phone 7 app and have a TextBlock defined like so:
<TextBlock Text="{StaticResource MY_TEXT}" TextWrapping="Wrap" Style="{StaticResource SubHeadingStyle}"/>
We have a resource defined like so:
<system:String x:Key="MY_TEXT">This is the first line of text.
This is the second line of text.</system:String>
We've tried all the ways we can think of to represent the line break in the XML, but whatever we try, it's either completely ignored, or appears on screen within the TextBlock.
We've isolated the problem to the loading of the resource dictionary - if we read the string from the resource dictionary programmatically, the line break has been replaced by a space character (0x20). Conversely, if we put a line break character in the Text property of the TextBlock in the XAML, it does appear.
Is there any way we can get the line break to appear correctly in our TextBlock while still using bindings, and without writing code to modify the value?

You have to Preserve WhiteSpace
<system:String xml:space="preserve" x:Key="PURCHASE_SUCCESS">This is the first line of text.
This is the second line of text.</system:String>

Related

DataGrid converts consecutive spaces into non-breaking spaces on copy

The Problem
Here's a strange little quirk I ran into that I'm not sure how to fix. When I copy data from a DataGridTextColumn, if the text contains more than one space character (U+0020) in a row, all spaces except the first will be replaced with non-breaking spaces (U+00A0) in the pasted text.
I'll mention that this only happens with certain paste destinations, the one of particular concern being Excel. But I've confirmed that the problem does lie in WPF and not in the destination, as I'll demonstrate in a moment.
Code to Reproduce
Here's a very simple app so you can reproduce the problem.
A simple class to hold a string:
Public Class Foo
Public Sub New(Bar As String)
Me.Bar = Bar
End Sub
Public ReadOnly Property Bar As String
End Class
The back-end of a window:
Public Class MainWindow
Public ReadOnly Property Foos As New List(Of Foo) From {New Foo("A B"),
New Foo("A B"),
New Foo("A B")}
End Class
And the front-end of the window:
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<DataGrid IsReadOnly="True" AutoGenerateColumns="False" ItemsSource="{Binding Foos}">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Bar}"/>
</DataGrid.Columns>
</DataGrid>
</Window>
Note that in the MainWindow back-end code, those spaces between the As and Bs are all just normal spaces (U+0020). The first Foo has one space, the second has two spaces, and the third has three.
It will also be helpful to have a clipboard viewing tool, so you can see the data that's being copied (I used Inside Clipboard), and a tool to list out the Unicode character codes in a string (I used this website).
Steps to Reproduce
Run MainWindow, select the second cell in the DataGrid and copy it using Ctrl+C.
If you paste this directly into the web tool I linked above, you will see only normal spaces, but open or refresh your clipboard viewer and you'll see there are different formats available:
If you inspect the first two formats CF_TEXT and CF_UNICODETEXT, you should see that the spaces between A and B are still normal spaces (you can copy those values from the clipboard viewer into the web tool to verify this). But if you look at the HTML Format entry, you'll see this:
And so we reach the problem: while the text formats are being encoded correctly, the HTML format is being encoded with non-breaking spaces.
You can also test this using Excel. Excel will favor the HTML format by default when pasting. If you copy that same second cell from the DataGrid into Excel, it will paste the string containing non-breaking spaces, which you can verify using a formula, some VBA code, or by copying the text from Excel into the web tool. If you try Paste Special in Excel instead of normal Paste, you have the option of choosing which format to use as a source. Using either Text or Unicode Text results in output strings with normal spaces, as intended.
How Can I Fix This?
So that's the problem, copying and pasting from the DataGrid into Excel changes the string, and I need the string to stay the same. I don't know why this behavior occurs or how I would go about changing it or working around it.

Silverlight TextBlock should wrap whole words only

I have multiple TextBlocks in a control. The blocks have a fixed width and the TextWrap property is set to Wrap. The text is provided via binding.
Right now the wrapping occurs when SL detects that it can't fit another character in the line. Which results in something like "The quick bro" \r\n "wn fox jumps".
But I want those blocks to wrap their text only at word boundaries and not at some random position in the middle of a word. The expected outcome should look something like "The quick brown" \r\n "fox jumps".
This is the XAML for one of the TextBlocks:
<TextBlock
x:Name="Foo"
Foreground="#FFD4E4FF"
FontSize="14.667"
FontFamily="Arial"
Canvas.Left="586.671"
LineHeight="23.707"
TextWrapping="Wrap"
Text="{Binding Bar}"
Canvas.Top="170"
Width="120" />
Any ideas?
We finally found the problem. For some reason the strings we loaded from the database contained characters that looked like regular blanks in the debugger and in text editors but where not treated as such by Silverlight. The character in question was a non-breaking space

Silverlight Stringformat : malformed string returns empty string instead of exception

Here's my code snippet :
<TextBox Text="{Binding Path=Amount, Mode=TwoWay, StringFormat=\{0:N\}}" />
If the user enters letters or a large number etc, the stringformat dies silently. How can i raise an exception instead ?
Thanks
Bindings swallow exceptions thrown when text input cannot be converted to the data type required by the property on source object. However you can specify ValidatesOnException in the binding. That will cause the standard red border reporting of a conversion problem. BTW this is unrelated to the string format property which is only relevant for displaying the current value, it isn't in play when user is entering data.
<TextBox Text="{Binding Path=Amount, Mode=TwoWay, StringFormat=\{0:N\}, ValidatesOnExceptions=True}" HorizontalAlignment="Left" Width="200"/>
Note I've limited the width and aligned to left. One of the problems with the default validation popup is that is that it is always displayed to the right, which is a bit of a problem when the text box right border is flush with the right edge of the silverlight control's right edge.
Have you thought of writing a filter behavior that allows you to control exactly what goes into the text box?

How to represent Line Break or new line in silverlight textBox

I am having hard time to match Special characters set in Silverlight. I only on the following:
To represent a LineBreak in Silverlight TextBlock:
use : > lineBreak <
But What do I use to represent a New Line or LineBreak In Silverlight TextBox??
Example : I want this one line mag : This is line one. This is line two
into this :
This is line one.
This is line two.
it seems this \r\n is not working. This is line one \r\n
The bottom line at the top
<TextBox Text="This is line one!
This is line two!" />
Linebreak Weirdness in the Silverlight TextBox
If you are going to be initialising content of a TextBox with literal text in Xaml in a similiar way that you might a TextBlock then you need a reliable way to represent the line break character the Silverlight uses in Xaml.
Silveright uses a CR character (0x0D - ASCII 13) to represent a linebreak which in C# you include in a string literal as \r. However Xaml isn't C# so you can't use \r in Xaml.
Xaml is fundementally XML but with some Xaml parsing oddities. Just including a linebreak, as Derek has in his answer, directly in the Xaml will not work at runtime (although the designer displays it as expected). You might think that this because Xml uses the LF character (0x0A) as its linebreak character. However in code you can assign a string containing "\r" or "\n" to the Text property and the TextBox will show a new line. In fact you can assign the sequence "\r\n" and it will show a single new line (not two new lines).
Ultimately you can use the Xml character code entity to represent a \r in Xaml "
" which survives the Xaml parsing process for reason which I cannot actually explain.
In XAML you can simply use the LineBreak:
<TextBlock Name="textBlock1" >line 1 <LineBreak /> line 2</TextBlock>
To add a line break to the Text property of a TextBox in XAML, use the ASCII character code for a linefeed as shown in the following example:
<TextBox x:Name="_test" Height="150" Text="This is line one.
This is line two." />
To add a line break to the Text property of a TextBox in code-behind, use the Environment.NewLine static value (which is the same as \r\n) as shown in the following code example:
this._test.Text = string.Format(
"This is line one.{0}This is line two.",
Environment.NewLine);
If you want to display a string with a carriage return in it, just use a string with a carriage return in it:
MyTextBlock.Text = #"line 1
line2";
Thank all.
It is working.
For Silverlight TextBlock: use <lineBreak/> in the XAML of textBlock.
Thank to AnthonyWJones
For Silverlight textBox, I use "\r" in the string which is used to display in TextBox.
For a line break in a Windows Phone Silverlight TextBlock use:
"This is line one!" & vbCrLf & "This is line two!"
<TextBox x:Name="textBox" AcceptsReturn="True" />

Multiline for WPF TextBox

I am developing an app for sending some feedback.
Basically I'm trying to make a TextBox for comments, but I'm used to the WinForms MultiLine=true. I've set MinLines to 3, which is getting there, but preferably I'd like it if the user is able to type wherever in this block - like press enter and do dot points sort of thing. For example:
- Item 1 blah
- Item 2 blahlb lahbvl d
But at the moment the text all stays on one line.
- Item 1 blah - Item 2 blahb blahb blah
These comments will then help fill the body of an email which is sent. It may be pointless if I can't easily keep the same formatting when putting this string into the email body string (so that it looks like it does when sent as it does when typed).
Can I achieve what I'm after or do I have to leave it as all text on one line?
Enable TextWrapping="Wrap" and AcceptsReturn="True" on your TextBox.
You might also wish to enable AcceptsTab and SpellCheck.IsEnabled too.
Also, if, like me, you add controls directly in XAML (not using the editor), you might get frustrated that it won't stretch to the available height, even after setting those two properties.
To make the TextBox stretch, set the Height="Auto".
UPDATE:
In retrospect, I think this must have been necessary thanks to a default style for TextBoxes specifying the height to some standard for the application somewhere in the App resources. It may be worthwhile checking this if this helped you.
Here is a sample XAML that will allow TextBox to accept multiline text and it uses its own scrollbars:
<TextBox
Height="200"
Width="500"
TextWrapping="Wrap"
AcceptsReturn="True"
HorizontalScrollBarVisibility="Disabled"
VerticalScrollBarVisibility="Auto"/>
The only property corresponding in WPF to the
Winforms property: TextBox.Multiline = true
is the WPF property:
TextBox.AcceptsReturn = true
or
<TextBox AcceptsReturn="True" ...... />
All other settings, such as VerticalAlignement, WordWrap etc., only control how the TextBox interacts in the UI but do not affect the Multiline behaviour.
Contrary to #Andre Luus, setting Height="Auto" will not make the TextBox stretch. The solution I found was to set VerticalAlignment="Stretch"

Resources