wpf中的弹出和切换按钮交互 [英] Popup and Togglebutton interaction in wpf

查看:14
本文介绍了wpf中的弹出和切换按钮交互的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含 Togglebutton 和 Popup 的控件.单击 ToggleButton 时,将出现弹出窗口.取消选中 ToggleButton 时,弹出窗口应关闭.此外,在弹出窗口之外单击应该会导致它关闭,并导致 Togglebutton 取消选中.

I have a control that contains a Togglebutton and a Popup. When the ToggleButton is clicked on, the popup appears. When the ToggleButton is unchecked, the popup should close. Additionally, clicking away from the popup should cause it to close, and cause the Togglebutton to uncheck.

我已通过将 Popup 的 StaysOpen 属性设置为 false 并将切换按钮的 IsChecked 属性设置为双向绑定到 Popup 的 IsOpen 属性来进行设置.

I've set this up by setting the StaysOpen property of the Popup to false, and setting the IsChecked property of the toggle button to be two-way bound to the IsOpen property of the Popup.

一切都很好,除了一种情况 - 选中按钮并打开弹出窗口,单击按钮不会导致弹出窗口关闭,或者按钮返回未选中状态.

All is well, apart from one case - with the button checked and the popup open, clicking the button does not cause the popup to close, or the button to return to unchecked.

我相信这一定是因为单击按钮会导致 Popup 的 StaysOpen 逻辑将 Popup 的 IsOpen 属性设置为 false.反过来,这会将 Togglebutton 设置为未选中.这必须在我点击按钮之前发生 - 所以点击重新检查按钮,即竞争条件.

I believe this must be because clicking the button causes the StaysOpen logic of the Popup to set the Popup's IsOpen property to false. In turn, this sets the Togglebutton to unchecked. This must happen before my click on the button is processed - so the click re-checks the button, ie a race condition.

知道如何获得我想要的行为吗?

Any idea how I can get the behaviour I want?

推荐答案

如果你的假设是正确的,你需要一个自定义的 Popup 类,如下所示:

If your assumption is correct, you'd need a custom Popup class like the following:

public class MyPopup : Popup {
    protected override void OnPreviewMouseLeftButtonDown(MouseButtonEventArgs e) {
        bool isOpen = this.IsOpen;
        base.OnPreviewMouseLeftButtonDown(e);

        if (isOpen && !this.IsOpen)
            e.Handled = true;
    }
}

您可能需要从 if 语句中删除 !this.IsOpen.如果您改用 MyPopup,它将阻止 MouseLeftButtonDown 事件到达 ToggleButton.

You may need to remove the !this.IsOpen from the if-statement. If you use MyPopup instead, it will prevent the MouseLeftButtonDown event from reaching the ToggleButton.

这篇关于wpf中的弹出和切换按钮交互的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆