Pollitzer
Pollitzer

Reputation: 1620

WPF combo box seems to cause InvalidCastException

Excerpt from Reference Source:

private void CloneLayoutUpdated(object sender, EventArgs e)
{
    Rectangle rect = (Rectangle)SelectionBoxItem;
    rect.Width = _clonedElement.RenderSize.Width;
    rect.Height = _clonedElement.RenderSize.Height;

    VisualBrush visualBrush = (VisualBrush)rect.Fill; // (x)
    visualBrush.Viewbox = new Rect(_clonedElement.RenderSize);
    visualBrush.Viewport = new Rect(_clonedElement.RenderSize);
}

I would claim line (x) to be buggy since rect.Fill might refer to a SolidColorBrush.

Has someone (simple?) Xaml / C# code to throw the exception?

Upvotes: 0

Views: 62

Answers (1)

Dave M
Dave M

Reputation: 3043

SelectionBoxItem is a read only dependency property. The creation of its actual value is handled internal to the ComboBox class and no value for it could come externally. If you inspect UpdateSelectionBoxItem method right above, you will see that the handler in question is only registered when SelectionBoxItem is set to a Rectangle that has a VisualBrush as it’s Fill. Therefore these casts are “safe”, rect.Fill will never refer to anything other than a VisualBrush when that event handler is called.

Upvotes: 1

Related Questions