eriksmith200
eriksmith200

Reputation: 2179

Ignoring while preserving line breaks in WPF TextBox

I want to present a string containing line breaks in a TextBox, but I want the TextBox to show it as a single line. Removing the line breaks is not an option; they need to be preserved, also after editing the text.

In the example below, when typing in the first TextBox, the text must be presented in the second TextBox in a single line. When editing the text in the second TextBox, the line breaks in the first TextBox must be preserved.

Does anyone know if this is possible?

<Grid Background="AliceBlue">
  <Grid.RowDefinitions>
     <RowDefinition Height="100"/>
     <RowDefinition Height="100"/>
  </Grid.RowDefinitions>

  <TextBox x:Name="FirstTextBox"
     AcceptsReturn="True"
     TextWrapping="Wrap"
     Text="{Binding MyString}" 
     Width="150"/>

  <TextBox x:Name="SecondTextBox"
     Grid.Row="1"
     AcceptsReturn="False"
     TextWrapping="NoWrap"
     Text="{Binding MyString}"
     VerticalAlignment="Top"/>
</Grid> 

Upvotes: 5

Views: 2305

Answers (2)

eriksmith200
eriksmith200

Reputation: 2179

I created a binding converter that works for my scenario: Line-breaks are replaced with the unicode zero width space character (U+200B):

public class IgnoreLinebreaksConverter : IValueConverter
{
    private const string Sub = " \u200B";
    private const string Lb = "\r\n";

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var s = (string)value;
        return string.IsNullOrEmpty(s) ? s : Regex.Replace(s, Lb, Sub);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var s = (string)value;
        return string.IsNullOrEmpty(s) ? s : Regex.Replace(s, Sub, Lb);
    }
}

Upvotes: 5

brunnerh
brunnerh

Reputation: 184296

You could text-encode the linebreaks using \n (using a Binding.Converter), then you can replace those sequences with actual line-breaks if needed (in ConvertBack), in terms of usability that would be questionable though.

Upvotes: 0

Related Questions