如果StaysOpen ="False",弹出窗口不会打开

Kel*_*sie 5 c# wpf xaml

如果我将StaysOpen更改为"True",弹出窗口会显示,但是当您在其外部单击时它不会关闭,因此这不是我想要的.

这是相关的XAML代码:

<Border x:Name="popupPlacementTarget">
    <i:Interaction.Behaviors>
        <local:PopupBehavior>
            <local:PopupBehavior.Popup>
                <Popup PlacementTarget="{Binding ElementName=popupPlacementTarget}"
                       Placement="MousePoint"
                       StaysOpen="False">
                    <ContentPresenter Content="{Binding SomeContent}" ContentTemplate="{StaticResource SomeContentTemplate}" />
                </Popup>
            <local:PopupBehavior.Popup>
        </local:PopupBehavior>
    </i:Interaction.Behaviors>
</Border>
Run Code Online (Sandbox Code Playgroud)

这是PopupBehavior代码:

public class PopupBehavior : Behavior<UIElement>
{
    #region Dependency Properties

    public static readonly DependencyProperty PopupProperty = DependencyProperty.Register(
        "Popup", typeof(Popup), typeof(PopupBehavior), new FrameworkPropertyMetadata(default(Popup)));

    #endregion Dependency Properties

    #region Properties

    public Popup Popup
    {
        get { return (Popup)this.GetValue(PopupProperty); }
        set { this.SetValue(PopupProperty, value); }
    }

    #endregion Properties

    #region Protected Methods

    protected override void OnAttached()
    {
        base.OnAttached();

        this.AssociatedObject.MouseDown += this.OnMouseDown;
    }

    protected override void OnDetaching()
    {
        base.OnDetaching();

        this.AssociatedObject.MouseDown -= this.OnMouseDown;
    }

    #endregion Protected Methods

    #region Private Methods

    private void OnMouseDown(object sender, MouseButtonEventArgs eventArgs)
    {
        var popup = this.Popup;
        if (popup == null)
        {
            return;
        }

        this.Popup.IsOpen = true;
    }

    #endregion Private Methods
}
Run Code Online (Sandbox Code Playgroud)

知道为什么我的弹出窗口不会出现StaysOpen ="False"吗?

Kel*_*sie 0

原来有一个祖先,在鼠标按下时乱抓捕获。现在我已经纠正了这个问题,一切都正常。

顺便说一句,我可以通过设置 StaysOpen="True"、继承 Popup 并挂钩到派生 Popup 中的全局鼠标事件来解决这个问题。当弹出窗口打开时,我会将处理程序附加到全局输入事件。然后,当收到事件时,我会对其进行过滤,以便仅响应鼠标左键按下事件。在处理此事件时,如果鼠标未悬停在弹出窗口上,我将关闭弹出窗口并分离该事件。它有效,但显然是一个肮脏的黑客,我很高兴我在没有它的情况下也能正常工作。