DEV Community

s-iguchi09
s-iguchi09

Posted on Edited on Originally published at s-iguchi09.github.io AI-assisted

Why WPF Input Limits Such as MaxLength Do Not Apply to Values Set from Code or Bindings

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

  1. These limits restrict the user, not the property. Assignment from code passed six of the seven. MaxLength, CharacterCasing, and PasswordBox.MaxLength are documented this way.
  2. DatePicker leaks even for users. A date outside the range typed into its text box became SelectedDate, and DisplayDateStart then moved back to that date.
  3. Slider.Maximum coerces only the screen. Set to 150 through a TwoWay binding, the slider showed 100 while the view model kept 150.
  4. 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)));
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)