Skip to content

Commit a5277eb

Browse files
authored
Make text in NumericUpDown update immediately when changing the TextConverter. (#21320)
1 parent f47606a commit a5277eb

2 files changed

Lines changed: 48 additions & 1 deletion

File tree

src/Avalonia.Controls/NumericUpDown/NumericUpDown.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -605,7 +605,7 @@ protected virtual void OnTextConverterChanged(IValueConverter? oldValue, IValueC
605605
{
606606
if (IsInitialized)
607607
{
608-
SyncTextAndValueProperties(false, null);
608+
SyncTextAndValueProperties(false, null, true);
609609
}
610610
}
611611

tests/Avalonia.Controls.UnitTests/NumericUpDownTests.cs

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,10 @@
33
using System.Globalization;
44
using System.Linq;
55
using System.Reactive.Subjects;
6+
using System.Text.RegularExpressions;
67
using Avalonia.Controls.Templates;
78
using Avalonia.Data;
9+
using Avalonia.Data.Converters;
810
using Avalonia.Threading;
911
using Avalonia.UnitTests;
1012
using Xunit;
@@ -99,6 +101,51 @@ public void NumberFormat_Is_Applied_Immediately()
99101
Assert.Equal(value.ToString(newNumberFormat), control.Text);
100102
});
101103
}
104+
105+
private class TestNumericUpDownValueConverter(string format) : IValueConverter
106+
{
107+
public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
108+
{
109+
var input = value?.ToString() ?? string.Empty;
110+
if (string.IsNullOrEmpty(input))
111+
return 0m;
112+
var numberPattern = new Regex("[0-9.,]+");
113+
var match = numberPattern.Matches(input).FirstOrDefault();
114+
if (match == null)
115+
return 0m;
116+
117+
return decimal.Parse(match.Value, CultureInfo.InvariantCulture);
118+
}
119+
120+
public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
121+
{
122+
if (value is not decimal inputNumber)
123+
return null;
124+
return inputNumber.ToString(format, CultureInfo.InvariantCulture);
125+
}
126+
}
127+
128+
[Fact]
129+
public void TextConverter_Is_Applied_Immediately()
130+
{
131+
RunTest((control, textbox) =>
132+
{
133+
const decimal value = 10.11m;
134+
var initialConverter = new TestNumericUpDownValueConverter("C2");
135+
var newConverter = new TestNumericUpDownValueConverter("P2");
136+
137+
// Establish and verify initial conditions.
138+
control.Value = value;
139+
control.TextConverter = initialConverter;
140+
var oldText = control.Text ?? string.Empty;
141+
Assert.Equal("¤10.11", oldText);
142+
143+
// Check that NumberFormat is applied.
144+
control.TextConverter = newConverter;
145+
var newText = control.Text ?? string.Empty;
146+
Assert.Equal("1,011.00 %", newText);
147+
});
148+
}
102149

103150
public static IEnumerable<object?[]> Increment_Decrement_TestData()
104151
{

0 commit comments

Comments
 (0)