我想在 TextBox 中显示一个包含换行符的字符串,但我希望 TextBox 将其显示为单行。删除换行符不是一种选择;在编辑文本之后也需要保留它们。
在下面的示例中,在第一个 TextBox 中键入时,文本必须在第二个 TextBox 中以单行显示。编辑第二个 TextBox 中的文本时,必须保留第一个 TextBox 中的换行符。
有谁知道这是否可能?
<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>
最佳答案
我创建了一个适用于我的场景的绑定(bind)转换器:换行符替换为 unicode 零宽度空格字符 (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);
}
}
关于wpf - 在 WPF 文本框中保留换行符时忽略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9115952/