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

  1. Clamp before assignment: box.Width = Math.Max(0, computedWidth)
  2. Validate the computed width and substitute an empty/default size when negative
  3. 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

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


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)