putting ContextMenu in WPF Styles

2019-07-14 14:07发布

问题:

I am trying to put ContextMenu in styles with below so that it can be shared by all textboxes.

<Grid.Resources>
            <Style x:Key="Cell" TargetType="TextBox">
                <Setter Property="Margin" Value="0"/>
                <Setter Property="BorderBrush" Value="Black"/>
                <Setter Property="BorderThickness" Value="0.2"/>
                <Setter Property="VerticalAlignment" Value="Stretch"/>
                <Setter Property="HorizontalAlignment" Value="Stretch"/>
                <Setter Property="MinHeight" Value="30"/>
                <Setter Property="MinWidth" Value="70"/>
                <Setter Property="ContextMenu">
                    <Setter.Value>
                        <ContextMenu>
                            <MenuItem Header="Level1" Click="SubLevel1_Click_1"/>
                            <MenuItem Header="SubLevel1"/>
                        </ContextMenu>
                    </Setter.Value>
                </Setter>
            </Style>

        </Grid.Resources>

This code works fine till I add Click event. When click event is added it Builds but throws following an exception when it is executed: 'Set connectionId threw an exception.' Line number '21' and line position '34'.

Am i doing something wrong here.

回答1:

Not sure what's causing this, but you can easily workaround this by putting ContextMenu as a separate resource:

<ContextMenu x:Key="ContextMenu">
    <MenuItem Header="Level1" Click="SubLevel1_Click_1"/>
    <MenuItem Header="SubLevel1"/>
</ContextMenu>
<Style TargetType="TextBox">
    <Setter Property="ContextMenu" Value="{StaticResource ContextMenu}"/>
</Style>