当用户点击它时关闭 WPF 弹出窗口

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12585789/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 05:32:29  来源:igfitidea点击:

Close WPF popup when user clicks on it

wpfxamlmvvmpopup

提问by Michael Matejko

How do I close the following popup when its content is clicked?

单击其内容时如何关闭以下弹出窗口?

<Button Name="myButton" Content="Hover to open" />
<Popup PlacementTarget="{Binding ElementName=myButton}" Placement="Bottom">
    <Popup.Resources>
        <DataConversion:BooleanOrConverter x:Key="booleanOrConverter" />
    </Popup.Resources>            
    <Popup.IsOpen>
        <MultiBinding Mode="OneWay" Converter="{StaticResource booleanOrConverter}">
            <Binding Mode="OneWay" ElementName="myButton" Path="IsMouseOver"/>
            <Binding RelativeSource="{RelativeSource Self}" Path="IsMouseOver" />
        </MultiBinding>
    </Popup.IsOpen>
    <!-- some content here -->
</Popup>

I wanted to avoid writing code in the code behind file and binding visual and behavioral things like IsOpen property or MouseDown event to the ViewModel.

我想避免在文件背后的代码中编写代码并将视觉和行为事物(如 IsOpen 属性或 MouseDown 事件)绑定到 ViewModel。

采纳答案by Tim Rogers

You need an EventTriggeron your Popupthat triggers a storyboard that contains a BooleanAnimationUsingKeyFramesthat sets IsOpento false, similar to this. Easier to just use code-behind ;o)

你需要一个EventTrigger在你的Popup触发包含一个故事板BooleanAnimationUsingKeyFrames,设置IsOpenfalse与此类似。更容易使用代码隐藏;o)

回答by H.B.

You could just make the Popup.Childa Button(style it to not look like one), handle its Clickevent and set IsOpento false(preferably using SetCurrentValueto not destroy the binding).

您可以只制作Popup.Childa Button(将其Click设置IsOpen为看起来不像一个),处理其事件并设置为false(最好使用SetCurrentValue不破坏绑定)。

You can either do this in code behind or using a behavior/trigger action.

您可以在后面的代码中执行此操作,也可以使用行为/触发器操作。