Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wpf- Unable to cast MenuItem to Listbox?

I am getting a very strange exception. I get the exception:

"'Set connectionId threw an exception.' Line number '26' and line position '34'."

When I look at the Inner Exception I get:

"Unable to cast object of type 'System.Windows.Controls.MenuItem' to type 'System.Windows.Controls.ListBox'."

I have narrowed the cause of the exception to the MenuItem in the TreeViewItem style contained in this TreeView:

<TreeView x:Name="ProjectElementTreeView" ItemsSource="{Binding ProjectElementCollection}"  DisplayMemberPath="Name" Padding="0" SelectedItemChanged="ProjectElementTreeView_SelectedItemChanged" GotKeyboardFocus="ProjectElementTreeView_GotKeyboardFocus">
        <TreeView.Resources>
            <Style TargetType="{x:Type TreeViewItem}">
                <Setter Property="HorizontalAlignment" Value="Left" />
                <Setter Property="ContextMenu">
                    <Setter.Value>
                        <ContextMenu>
                            <MenuItem Name="AddProjectElementMenuItem" Header="Add" Click="AddProjectElementMenuItem_Click"/>
                        </ContextMenu>
                    </Setter.Value>
                </Setter>
            </Style>
        </TreeView.Resources>
    </TreeView>

The exception only occurs when the MenuItem has a click event handler and is thrown even when the click event handler does not contain any code.

like image 667
Justin Avatar asked Dec 19 '10 21:12

Justin


2 Answers

I got the same exception as you did. After looking closer at the code, this feels like a situation where you would get

"The event 'Click' cannot be specified on a Target tag in a Style. Use an EventSetter instead."

I'm not sure why that doesn't apply here.
Anyway, using an EventSetter works

<Setter Property="ContextMenu">
    <Setter.Value>
        <ContextMenu>
            <MenuItem Name="AddProjectElementMenuItem" Header="Add">
                <MenuItem.Style>
                    <Style TargetType="MenuItem">
                        <EventSetter Event="Click" Handler="AddProjectElementMenuItem_Click"/>
                    </Style>
                </MenuItem.Style>
            </MenuItem>
        </ContextMenu>
    </Setter.Value>
</Setter>
like image 163
Fredrik Hedblad Avatar answered Oct 21 '22 04:10

Fredrik Hedblad


I had to face this weird situation myself. There is an easy way to get over it, you have to clean and rebuild the project and the exception will go away.


Hope this helps.

like image 45
Alex Stanciu Avatar answered Oct 21 '22 03:10

Alex Stanciu