Multiline for WPF TextBox - wpf

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"

Related

wpf - how to keep a control from being selected through tabbing [duplicate]

How do I set tab ordering in WPF? I have an ItemsControl with some items expanded and some collapsed and would like to skip the collapsed ones when I'm tabbing.
Any ideas?
If you want to explicitly set the tab ordering for elements in your form, the following attached property is supposed to help:
<Control KeyboardNavigation.TabIndex="0" ... />
I say "supposed to help" as I haven't found it very reliable though I probably need to read more about how it is intended to be used. I only post this half baked answer because no one else mentioned this property.
Note that in Win RT, the property is just TabIndex="0".
You can skip elements in the tab sequence by setting KeyboardNavigation.IsTabStop on the element in XAML.
KeyboardNavigation.IsTabStop="False"
You can setup a trigger that would toggle this property based on the expanded state.
<Control KeyboardNavigation.TabIndex="0" ... /> Works perfectly fine...
For example-
<ComboBox Height="23"
Margin="148,24,78,0"
Name="comboBoxDataSet"
VerticalAlignment="Top"
SelectionChanged="comboBoxDestMarketDataSet_SelectionChanged"
DropDownOpened="comboBoxDestMarketDataSet_DropDownOpened"
KeyboardNavigation.TabIndex="0" />
<ComboBox Height="23"
Margin="148,56,78,0"
Name="comboBoxCategory"
VerticalAlignment="Top"
SelectionChanged="comboBoxDestCategory_SelectionChanged"
DropDownOpened="comboBoxDestCategory_DropDownOpened"
KeyboardNavigation.TabIndex="1" />
Will allow you to navigate through these two combo boxes using TAB key.
I think there is a much easier solution here,
at the top within your control or window or whatever, you could add:
KeyboardNavigation.TabNavigation="Cycle"
This also automaticaly ignores the collapsed tabs.
Another alternative that has worked for me in the past is to simply remove all explicit TabIndex statements, and let the controls use the order that they're declared in XAML work their magic.
This, of course, may require you to reorder your controls. But this is a simple copy-paste operation.
You can use KeyboardNavigation.TabNavigation="None" to completely skip the Tabbing for specific control.

XAML - Relatively Position Control Outside of Document Flow

I'm looking to create a UI element in a WPF XAML UserControl with something that looks and works roughly like Google Suggest - a TextBox with a ListBox that appears beneath it showing suggestions that match the text entered in the TextBox. In simplified form, my XAML looks like this:
<StackPanel>
[...controls above...]
<TextBox ... />
<ListBox ItemsSource="{Binding SearchHints}"
Visibility="{Binding HasSearchHints}" MaxHeight="100" />
[...controls below...]
</StackPanel>
What I'm struggling to achieve is I want the ListBox to float above any content that may come below it, much like the dropdown part of a ComboBox does. Currently it pushes any controls below it downwards. I figure this must be possible because the ComboBox control essentially does exactly what I want to do. In CSS it would be a matter of setting the element to position:relative but there doesn't seem to be an immediately obvious equivalent in XAML. Any ideas?
Used Icepickle's comment - the element did exactly what I wanted.

How does WPF handle binding to the property of a null object?

I have a listBox using an itemTemplate that contains the following line:
<Image Source="{Binding MyProperty.PossiblyNullObject.UrlProperty}"/>
Bound to this listBox is a model view collection that loads components of the items in the collection on a separate thread. The 'PossiblyNullObject' may not be set to a value when the xaml code is first rendered by the composition engine.
How does WPF handle this? Does it use a default value(no image source so no image) and continue on? Does it wait? Does it automatically detect when the value is initialized and rerenders with the new source? How does it not throw object null exceptions in the same way it would if I called 'MyProperty.PossiblyNullObject.UrlProperty' programmatically? How can I reproduce this functionality in my own code when I try to call it?
Thanks for any suggestions. I am embarrassingly new to WPF and I'm trying to tackle a problem out of my depth. The image load is a perf problem so I found a solution to load, decode, then freeze the image source on a background thread so it wouldn't lock up the UI. Unfortunately, I ran across this null exception problem when I tried replacing the image source binding with my solution that calls the same property. WPF somehow handles the possible null objects and I'd like to do it the same way to keep things clean.
In BindingBase have two properties: TargetNullValue and FallbackValue.
TargetNullValue returns your value when the value of the source is null.
FallbackValue returns your value when the binding is unable to return a value.
Example of using:
<!-- xmlns:sys="clr-namespace:System;assembly=mscorlib" -->
<Window.Resources>
<!-- Test data -->
<local:TestDataForImage x:Key="MyTestData" />
<!-- Image for FallbackValue -->
<sys:String x:Key="ErrorImage">pack://application:,,,/NotFound.png</sys:String>
<!-- Image for NULL value -->
<sys:String x:Key="NullImage">pack://application:,,,/NullImage.png</sys:String>
</Window.Resources>
<Grid DataContext="{StaticResource MyTestData}">
<Image Name="ImageNull"
Width="100"
Height="100"
Source="{Binding Path=NullString, TargetNullValue={StaticResource NullImage}}" />
<Image Name="ImageNotFound"
Width="100"
Height="100"
Source="{Binding Path=NotFoundString, FallbackValue={StaticResource ErrorImage}}" />
</Grid>
See this links, for more information:
BindingBase.TargetNullValue Property
BindingBase.FallbackValue Property
Note: The upvoted and accepted answer does not answer the question; it explains how you can get {Binding A} to work if A is null, which is trivial to handle anyway, but it does not explain what happens and how to handle the much more interesting case of {Binding A.B} when A is null, and that is specifically what the question is asking. What follows is the answer to the question as stated.
WPF generally handles the case where A is null when you use A.B in a binding; I have not tried specifically with <Image Source>, but I have tried with <DataGrid ItemsSource> and with <Button Command>.
When WPF handles these cases, what I have observed happening is that there is no error or warning in the output window, and the application malfunctions a bit, but it does not crash:
In the case of <DataGrid ItemsSource>, the DataGrid appears empty.
In the case of a <Button Command>, the button is clickable, but when you click it nothing happens.
In the case of <Image Source> I would expect that no image will appear.
(Note that all these are cases of silent failure, so whoever decided that WPF should behave this way should be shot by firing squad at the central square with great celebrations and live music and big giveaways.)
The way we generally handle these cases depends on the nature of the element at hand.
For images, if an empty image is acceptable, then you do not need to do anything. If some image must be shown despite the property being null, then the accepted answer probably provides a solution.
For grids, not showing anything when the property is null is probably the desired behavior.
For buttons, the solution is to use an additional binding to the IsEnabled property of the button.
So, for example:
<Button Command="{Binding A.B}" IsEnabled="{Binding HasA}"/>
Where HasA is defined in the viewmodel as follows:
bool HasA => A != null;

how to do I Silverlight read-only edit control, which I can cut and paste from?

I have a master-detail view, which I created in Silverlight 2. So, I'm not using the new master-detail stuff available in SL3.
So basically you have a grid at the top, and at the bottom you have the details for whatever item you select in the grid appearing in a panel.
I did not want the user to be able to accidentally change the values in the fields, so I went with labels.
the user asked for cut and paste :)
Because I could not get the focus of that label, I implemented a non standard cut and paste solution by having the user right click in the label, and it puts it on the clipboard. The user then can do Ctrl+V to paste it somewhere else or in any other windows app.
However, now there are some users saying they need to be able to select a part of the item in the label, say the first 3 characters or the last 2 using the mouse or keyboard. So, it seems like the label needs to be replaced with an textbox control.
The problem doing this seems to be that if I set the textbox to readonly I cannot cut and paste from it. So, sure it's a textbox, and you cannot edit it, but you cannot copy/select from it either.
Is there another way to do this?
thanks for any help you can provide,
Sincerely,
J__
TextBox should be fine. I can't speak for Silverlight 2, and maybe there's an issue with SL2 and TextBox, but I just built a sample Silverlight 3 app, added a TextBox, and set Text="some text" and IsReadOnly="True". I'm able to select any portion of the text (via mouse), and ctrl-c it to put it on the clipboard.
Here's the (very simple) xaml I set up, with no code-behind. I'm able to select any portion of the text and copy it to the clipboard:
<UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="layouttest.MainPage"
Width="640" Height="480">
<Grid x:Name="LayoutRoot" Background="White">
<TextBox Width="200" Height="30" Text="See if you can copy this"
TextWrapping="Wrap" IsReadOnly="True" />
</Grid>

WPF: Use SpellCheck On Read-Only TextBox

I'm looking to display text with the wavey red lines where a word is misspelt, but I only want the text to be selectable, not editable. If I set the TextBox's IsReadOnly property to True or IsEnabled to False, the wavey red lines disappear and I can't get around it by putting something transparent as this will prevent the user being able to select sections of the text.
Is there anyway I can keep the red lines, allow the text to be selectable but prevent the actual text being modified?
Thanks
You could hook up to on the text change event of the text box, and just reject the new text. It would have the same effect of readonly without graying out the textbox or getting rid of the spell checking.
Thanks David. I'm currently looking at 2 possible solutions, yours and the following:
I've created a custom control which is based on the standard TextBox, but effectively has 2 textboxes laid on top of one another in this manor:
<TextBox Name="tbxBack"
Foreground="Transparent"
SpellCheck.IsEnabled="True"
TextWrapping="Wrap"
SnapsToDevicePixels="True"/>
<TextBox Name="tbxFront"
Background="Transparent"
TextWrapping="Wrap"
SnapsToDevicePixels="True"
IsReadOnly="True"/>
I think it's pretty straight forward what's going on here, but I'm concerned about the potential overhead this will cause.
The reason I'm looking into the double TextBox solution is that I'm worried if I try and cancel the event, it could end up with some sort of flashing in the control when the text is changed.

Resources