UWP TextBox.SelectedText将\ r \ n更改为\ r \ n
我需要获取TextBox的SelectedText
的字符,但我不能让SelectionStart与TextBoxes的Text属性匹配,显然是因为TextBox的SelectedText擦除了\n
值。
我有一个Windows 10 UWP应用程序。 我添加了两个TextBox和一个Button,如下面的XAML所示:
我通过在第一个TextBox中放入一些文本来初始化Page。
public MainPage() { this.InitializeComponent(); } private void Page_Loaded(object sender, RoutedEventArgs e) { this.textBox.Text = @"Call me Ishmael. Some years ago--never mind how long precisely--having little or no money in my purse, and nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the world. It is a way I have of driving off the spleen and regulating the circulation. Whenever I find myself growing grim about the mouth; whenever it is a damp, drizzly November in my soul; whenever I find myself involuntarily pausing before coffin warehouses, and bringing up the rear of every funeral I meet; and especially whenever my hypos get such an upper hand of me, that it requires a strong moral principle to prevent me from deliberately stepping into the street, and methodically knocking people's hats off--then, I account it high time to get to sea as soon as I can."; }
我希望以下内容可以得到所选内容(同样,我不需要SelectedText;我需要以前的字符,但我抓住这里选择的内容以便更容易理解):
private void Button_Click(object sender, RoutedEventArgs e) { textBox2.Text = textBox.Text.Substring(textBox.SelectionStart, 20 < textBox.SelectionLength ? 20 : textBox.SelectionLength); }
事实并非如此。 奇怪的是,似乎根据textBox.Text
到SelectionStart
,该值不包括\n
。 这就是我的意思……
如果我突出前两行……
叫我以实玛利。 几年前 – 没关系多长时间 – 我的钱包里有很少钱或没有钱,没有什么特别令我感兴趣的是岸上,我
…事情有效,我得到了我期望的东西(“叫我以实玛利。索姆”)。 但随着每一次下降,我得到的性格比我预期的多一个。 所以第2行和第3行首先给出换行符( \n
额外):
如果我们跳到第4和第5行(所以我们跳过三行),在选择之前我会得到三个字符。
也就是说,选择这个……
我有一种驱逐脾脏和调节血液循环的方法。 每当我发现自己的嘴巴变得严峻时; 无论什么时候潮湿,毛毛雨
……给这个……
小号\ r \ n
我有一种方式
(注意:我已经突出显示了这里手动选择的内容,只是为了帮助可视化正在发生的事情。)
如果我检查SelectedText
,每个换行都会减少到\r
,所以这几乎是有意义的,除了textBox.Text
仍然有平台适当的\r\n
而不是!
也就是说,如果我在Button_Click
事件中放置一个断点,并检查textBox.SelectedText
,我得到……
"a way I have of driving off the spleen and regulating the circulation. Whenever\rI find myself growing grim about the mouth; whenever it is a damp, drizzly\r"
只看到\r
? 然而textBox.Text
给出了……
"Call me Ishmael. Some years ago--never mind how long precisely--having little\r\nor no money in my purse, and nothing particular to interest me on shore, I\r\n[...]"
如果我想得到我期望的东西,我可以做些傻事……
public static string NormalizeNewlineToCarriageReturn(this string str) { str = str.Replace("\r\n", "\r"); str = str.Replace("\n", "\r"); return str; }
然后…
private void Button_Click(object sender, RoutedEventArgs e) { textBox2.Text = textBox.Text.NormalizeNewlineToCarriageReturn().Substring(textBox.SelectionStart, 20 < textBox.SelectionLength ? 20 : textBox.SelectionLength); }
但那太疯狂了 。 如果TextBox开始像我期望的那样开始工作,那就会破坏。
这是怎么回事? 我的意思是,我看到解释(像Skeet先生一样)似乎是短路到“你需要使用NewLine
”来解释TextBoxes中缺少的\n
,但至少在UWP中,我认为它比那更复杂。