Skip to content

Commit

Permalink
fix: Update text according to AcceptsReturn
Browse files Browse the repository at this point in the history
  • Loading branch information
Youssef1313 committed Oct 6, 2021
1 parent 28b08e5 commit d318146
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -94,13 +94,13 @@ public void When_BeforeTextChanging_Cancel()
var textChangingCount = 0;
var beforeTextChangingCount = 0;
textBox.BeforeTextChanging += (tb, e) =>
{
beforeTextChangingCount++;
if (e.NewText == "Papaya")
{
e.Cancel = true;
}
};
{
beforeTextChangingCount++;
if (e.NewText == "Papaya")
{
e.Cancel = true;
}
};
textBox.TextChanging += (tb, e) => textChangingCount++;
textBox.Text = "Chirimoya";
Assert.AreEqual("Chirimoya", textBox.Text);
Expand All @@ -116,6 +116,31 @@ public void When_BeforeTextChanging_Cancel()
Assert.AreEqual(2, beforeTextChangingCount);
}

[TestMethod]
public void When_Multi_Line_Text_And_Not_AcceptsReturn()
{
var textBox = new TextBox();
Assert.AreEqual(false, textBox.AcceptsReturn);
textBox.Text = "Hello\nWorld";
Assert.AreEqual("Hello", textBox.Text);

textBox.Text = "Hello\rWorld";
Assert.AreEqual("Hello", textBox.Text);
}

[TestMethod]
public void When_Multi_Line_Text_And_Not_AcceptsReturn_After_Text_Was_Set()
{
var textBox = new TextBox();

textBox.AcceptsReturn = true;
textBox.Text = "Hello\nWorld";
Assert.AreEqual("Hello\nWorld", textBox.Text);

textBox.AcceptsReturn = false;
Assert.AreEqual("Hello", textBox.Text);
}

public class MySource : System.ComponentModel.INotifyPropertyChanged
{
private string _sourceText;
Expand Down
31 changes: 30 additions & 1 deletion src/Uno.UI/UI/Xaml/Controls/TextBox/TextBox.cs
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,20 @@ public string Text
}
}

private static string GetSingleLine(string value)
{
for (int i = 0; i < value.Length; i++)
{
var c = value[i];
if (c == '\r' || c == '\n')
{
return value.Substring(0, i);
}
}

return value;
}

public static DependencyProperty TextProperty { get; } =
DependencyProperty.Register(
"Text",
Expand Down Expand Up @@ -265,14 +279,19 @@ private object CoerceText(object baseValue)
return DependencyProperty.UnsetValue;
}

if (!AcceptsReturn)
{
baseString = GetSingleLine(baseString);
}

var args = new TextBoxBeforeTextChangingEventArgs(baseString);
BeforeTextChanging?.Invoke(this, args);
if (args.Cancel)
{
return DependencyProperty.UnsetValue;
}

return baseValue;
return baseString;
}

#endregion
Expand Down Expand Up @@ -404,6 +423,16 @@ public bool AcceptsReturn

private void OnAcceptsReturnChanged(DependencyPropertyChangedEventArgs e)
{
if (e.NewValue is false)
{
var text = Text;
var singleLineText = GetSingleLine(text);
if (text != singleLineText)
{
Text = singleLineText;
}
}

OnAcceptsReturnChangedPartial(e);
UpdateButtonStates();
}
Expand Down

0 comments on commit d318146

Please sign in to comment.