当IsChecked属性将状态更改为True时,在ToggleButton上打开ContextMenu

时间:2012-03-01 15:46:45

标签: wpf

当IsChecked设置为true时,我想打开ToggleButton.ContextMenu。

我在下面编写代码,但是ContextMenu.IsOpen没有改变:

<ToggleButton x:Name="btnRegularButton"            
                      Content="Regular Button">

            <ToggleButton.Style>
                <Style TargetType="ToggleButton">
                    <Style.Triggers>

                        <Trigger Property="IsChecked" Value="True">
                            <Setter Property="ContextMenu.IsOpen" Value="True" />
                        </Trigger>

                    </Style.Triggers>
                </Style>
            </ToggleButton.Style>

            <ToggleButton.ContextMenu>

                <ContextMenu>                                                      
                    <MenuItem Header="Save" />
                    <MenuItem Header="Print" />
                    <Separator />
                    <MenuItem Header="Exit" />
                </ContextMenu>
            </ToggleButton.ContextMenu>

        </ToggleButton>

1 个答案:

答案 0 :(得分:0)

<Window x:Class="Staticoverflow.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Window.Resources>
    <ContextMenu x:Key="ContextMenu1">
        <MenuItem Header="Save" />
        <MenuItem Header="Print" />
        <Separator />
        <MenuItem Header="Exit" />
    </ContextMenu>
</Window.Resources>
<Grid>
    <Grid.RowDefinitions >
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    <ToggleButton x:Name="btnRegularButton"            
                  Content="Regular Button">

        <ToggleButton.Style>
            <Style TargetType="ToggleButton">
                <Style.Triggers>
                    <Trigger Property="IsChecked" Value="True">
                        <Setter  Property="ContextMenu"  Value="{StaticResource ContextMenu1}" />
                    </Trigger>
                </Style.Triggers>
            </Style>
        </ToggleButton.Style>


    </ToggleButton>

</Grid>

希望这会有所帮助。