dotnet/wpf · error · ArgumentException
SR.Rect_WidthAndHeightCannotBeNegative
Error message
SR.Rect_WidthAndHeightCannotBeNegative
What it means
The Width setter of WPF's internal SizeBox enforces the non-negative dimension invariant: assigning a negative value throws ArgumentException (SR.Rect_WidthAndHeightCannotBeNegative). This keeps cached boxed sizes valid, since a negative width is not a legal Size dimension in WPF.
Solutions
- Clamp before assignment: box.Width = Math.Max(0, computedWidth)
- Validate the computed width and substitute an empty/default size when negative
- Fix the upstream calculation that produces the negative width
Example fix
// before box.Width = availableWidth - totalPadding; // may be negative -> ArgumentException // after box.Width = Math.Max(0, availableWidth - totalPadding);
Defensive patterns
Strategy: validation
Validate before calling
if (width >= 0)
{
box.Width = width;
}
else
{
box.Width = 0; // or skip the assignment
} Type guard
static bool IsValidWidth(double width)
=> !double.IsNaN(width) && width >= 0; Try / catch
try
{
box.Width = computedWidth;
}
catch (ArgumentException)
{
box.Width = 0;
} Prevention
- Assign Math.Max(0, value) instead of raw computed widths
- Filter out sentinel values like -1 before assignment
- Centralize size computations in one helper that guarantees non-negative output
When it happens
Trigger: Setting SizeBox.Width to any value < 0, usually a width derived from layout arithmetic (available minus padding/margins) without clamping.
Common situations: Negative results from subtracting chrome/decorations from available space; uninitialized or sentinel values (-1) being assigned as a real width; data-driven widths computed from unvalidated input.
Related errors
- Width and Height cannot be negative.
- SR.Format(SR.InvalidCtorParameterNoNegative, "value")
- 0x80040206
- args
- args
AI-assisted analysis of dotnet/wpf@81131a70a4 (2026-09-14).
Data as JSON: /api/errors/80202626c3844180.
Report an issue: GitHub.
Appendix: source
Thrown at src/Microsoft.DotNet.Wpf/src/PresentationFramework/MS/Internal/KnownBoxes.cs:33
}
_width = width;
_height = height;
}
internal SizeBox(Size size): this(size.Width, size.Height) {}
internal double Width
{
get
{
return _width;
}
set
{
if (value < 0)
{
throw new System.ArgumentException(SR.Rect_WidthAndHeightCannotBeNegative);
}
_width = value;
}
}
internal double Height
{
get
{
return _height;
}
set
{
if (value < 0)
{
throw new System.ArgumentException(SR.Rect_WidthAndHeightCannotBeNegative);
}View on GitHub (pinned to 81131a70a4)