WPF中的Popup和Togglebutton交互 [英] Popup and Togglebutton interaction in wpf

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

问题描述

我有一个包含Togglebutton和Popup的控件.单击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.反过来,这会将切换"按钮设置为未选中.这必须在我对按钮的点击得到处理之前发生-因此点击会重新检查按钮,即比赛条件.

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中的Popup和Togglebutton交互的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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