当失去焦点时,使WPF控制消失

时间:2014-03-12 13:23:49

标签: wpf

我有一个StackPanel,用作其他菜单控件的容器。我希望StackPanel在点击UI上的其他位置时消失(类似于典型的菜单/上下文菜单)。我正在努力解决这个问题。有什么建议?我已经尝试了类似下面的样式的事件触发器,但它似乎无法正常工作。

<StackPanel.Style>
    <Style TargetType="{x:Type StackPanel}">
        <Style.Triggers>
            <EventTrigger RoutedEvent="LostMouseCapture" >
                <BeginStoryboard>
                    <Storyboard>
                        <DoubleAnimation From="1" To="0" Duration="0:0:0.1"
                                         Storyboard.TargetProperty="Opacity"/>
                    </Storyboard>
                </BeginStoryboard>
            </EventTrigger>
        </Style.Triggers>
    </Style>
</StackPanel.Style>

1 个答案:

答案 0 :(得分:0)

像这样设置stackPanel的触发器:

<EventTrigger RoutedEvent="MouseEnter" >
    <BeginStoryboard>
        <Storyboard>
            <DoubleAnimation To="1" Duration="0:0:0.1"
                    Storyboard.TargetProperty="Opacity"/>
        </Storyboard>
    </BeginStoryboard>
</EventTrigger>

并将此标记添加到Window(以及单击时想要的其他控件,隐藏堆栈面板):

<Window.Triggers>
    <EventTrigger RoutedEvent="MouseDown">
        <BeginStoryboard>
            <Storyboard>
                <DoubleAnimation To="0" Duration="0:0:0.1"
                                 Storyboard.TargetName="disappearingStackPanel"
                                 Storyboard.TargetProperty="Opacity"/>
            </Storyboard>
        </BeginStoryboard>
    </EventTrigger>
</Window.Triggers>

您还可以在没有鼠标交互的控件上设置IsHitTestVisible=False,这样您就不必为它们添加触发器。