A TextBox has MaxLength="50", yet an 80-character name loaded from an old record shows up in full and gets saved again. The same happens with a DatePicker range, a snapping Slider, and a disabled TabItem.
This is a short summary. The full article, with tables for seven limits across user input, code, and bindings on .NET 10, is here:
Why WPF Input Limits Such as MaxLength Do Not Apply to Values Set from Code or Bindings
What the measurements show
-
These limits restrict the user, not the property. Assignment from code passed six of the seven.
MaxLength,CharacterCasing, andPasswordBox.MaxLengthare documented this way. -
DatePickerleaks even for users. A date outside the range typed into its text box becameSelectedDate, andDisplayDateStartthen moved back to that date. -
Slider.Maximumcoerces only the screen. Set to150through aTwoWaybinding, the slider showed100while the view model kept150. -
A disabled tab is still selectable by setting
SelectedIndex.
The fix
Guard the value in the view model, and keep the control limits only as typing aids. For a length, record an error through INotifyDataErrorInfo instead of truncating:
_nameErrors.Clear();
if (value.Length > MaxNameLength)
_nameErrors.Add($"Name must be at most {MaxNameLength} characters.");
ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(nameof(Name)));
For a volume, clamp and round in the setter so the source and the slider agree. The full article also explains why a read-only period needs Mode=OneWay on DisplayDateStart.
A Japanese version is also available.
Related Articles
- Why WPF Validation Errors Are Not Displayed, and Choosing Between IDataErrorInfo and INotifyDataErrorInfo
- How User Input Silently Removes a WPF Binding Written Without Mode
- Why a WPF DataGrid Edit Does Not Reach the ViewModel When Save Is Clicked, and How to Use CommitEdit
- Exceptions WPF's DispatcherUnhandledException Never Sees — Where Thread, Task and async void Exceptions Go
- TextBox (WPF Standard Control Demo App)
- PasswordBox (WPF Standard Control Demo App)
- DatePicker (WPF Standard Control Demo App)
- Slider (WPF Standard Control Demo App)
- TabItem (WPF Standard Control Demo App)
Top comments (0)