在 WPF 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>
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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我创建了一个适合我的场景的绑定转换器:换行符被替换为 unicode 零宽度空格字符 (U+200B):
I created a binding converter that works for my scenario: Line-breaks are replaced with the unicode zero width space character (U+200B):
您可以使用
\n
对换行符进行文本编码(使用Binding.Converter
),然后您可以根据需要用实际换行符替换这些序列(在ConvertBack
中),按照但可用性值得怀疑。You could text-encode the linebreaks using
\n
(using aBinding.Converter
), then you can replace those sequences with actual line-breaks if needed (inConvertBack
), in terms of usability that would be questionable though.