Ben Bancroft
Ben Bancroft

Reputation: 105

Why do I get InvalidCastException when I open then close the Menu on my Window?

When I create a new WPF Application in NET Framework 4.7.2 add a Menu to the MainWindow I get the InvalidCastException whenever you click on the menu and then click away from the menu to close it.

I can ignore this exception when it is thrown from PresentationFramework.dll and all is well I am just interested as to whether this is a NET Framework issue or something I have got wrong?

Entire solution can be found here https://github.com/glrad/InvalidCastException

App.xaml.cs

protected override void OnStartup(StartupEventArgs e)
{
    var view = new MainWindow();
    MainWindow = view;
    view.Show();
}

MainWindow.xaml

<Window x:Class="MyApplication.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="GASGC3" Height="800" Width="1000">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <Menu Grid.Row="0">
            <MenuItem Header="File">
                <MenuItem Header="Options" InputGestureText="Ctrl+O"/>
                <Separator/>
                <MenuItem Header="Exit" InputGestureText="Alt+F4" />
            </MenuItem>
            <MenuItem Header="Help">
                <MenuItem Header="About" />
            </MenuItem>
        </Menu>
    </Grid>
</Window>

Exception thrown:

System.InvalidCastException: 'Unable to cast object of type 'System.Collections.Hashtable' to type 'System.String'.'

Upvotes: 3

Views: 1443

Answers (1)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112299

It seems that you see this exception because you have changed the Exception Settings in Visual Studio and enabled CLR exceptions.

If you check Break when thrown: Common Language Runtime Exceptions, then you will see exceptions that are caught and would otherwise never bubble up to the user. These exceptions are normal.

You should enable breaking on CLR exceptions only when you are tracking hard to find bugs. Usually you even set a breakpoint, start the app with CLR exceptions off (to avoid running into them all the time), then, when the breakpoint is hit, check this option and continue to test only specific code. Usually you do this, if you want to see exceptions that you have handled and swallowed silently in a try-catch statement.

Note, this shows handled exceptions, so don't worry about them.

Upvotes: 1

Related Questions