I have a textbox that i am binding to the viewmodel's string property. The string property is updated within the viewmodel and it displays the text within the textbox through binding.
The issue is that i want to insert the line break after a certain number of characters in the string property and i want that the line break is shown over the textbox control.
I tried appending \r\n inside the string property in viewmodel but the line break is not reflected over the textbox (i have Acceptsreturn property set to true inside the textbox)
Can anybody help.
The solution for me was to use HTML encoded line feeds ( ).
Line1 Line2
Looks like
Line1
Line2
From Naoki
I just created a simple app that does what you describe, and it worked for me.
XAML:
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition />
</Grid.RowDefinitions>
<TextBox Grid.Row="0" AcceptsReturn="True" Height="50"
Text="{Binding Path=Text, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
<Button Grid.Row="1" Click="Button_Click">Button</Button>
</Grid>
</Window>
ViewModel:
class ViewModel : INotifyPropertyChanged
{
private string text = string.Empty;
public string Text
{
get { return this.text; }
set
{
this.text = value;
this.OnPropertyChanged("Text");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propName)
{
var eh = this.PropertyChanged;
if(null != eh)
{
eh(this, new PropertyChangedEventArgs(propName));
}
}
}
An instance of ViewModel
is set as the DataContext
for the Window
. Finally, the implementation of Button_Click()
is:
private void Button_Click(object sender, RoutedEventArgs e)
{
this.model.Text = "Hello\r\nWorld";
}
(I realize that the view shouldn't really modify the ViewModel's Text
property directly, but this is just a quick sample app.)
This results in the word "Hello" on the first line of the TextBox
, and "World" is on the second line.
Maybe if you post your code we can see what is different from this sample?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With