WPF - 如何组合框知道什么时候关闭下拉菜单 [英] WPF - How Combobox knows when to close the drop down menu

查看:448
本文介绍了WPF - 如何组合框知道什么时候关闭下拉菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写类似组合框控制,我想知道如果任何人知道如何检测时组合框外,用户点击边界。该组合框关闭它的下拉列表在这种情况下。

I want to write a control similar to ComboBox and I'm wondering if anybody knows how to detect when a user clicks outside the ComboBox boundaries. The ComboBox closes it's dropdown in this situation.

推荐答案

我有同样的问题在很多年前与​​Silverlight的早期版本。我检查了控件模板和反编译微软code地发现,他们使用一种无​​形的覆盖整个窗口来检测的点击。在WPF组合框似乎并没有以同样的方式,但是你可以按照Silverlight的模式。

I had the same question many years ago with an early version of Silverlight. I examined the control template and decompiled the Microsoft code to find that they were using an invisible overlay across the entire window to detect clicks. The WPF comboBox does not seem to work the same way, but you can follow the Silverlight pattern.

您将需要创建一个矩形,它是大小相同的窗口。我这样做是通过使用ROWSPAN覆盖保存我的整个应用程序的主电网。你也可以绑定高度/宽度以窗口的高度/宽度。有一打的方式来做到这一点,只是让它填满整个窗口。为矩形白色的填充颜色和0的透明度确实也需要填充颜色与透明度= 0但是工作的用户不会看到它。为了调试的目的,你可以给它红色和不透明0.25。

You'll want to create a rectangle that is the same size as your window. I do this by using a RowSpan to cover the primary Grid that holds my entire application. You could also bind the Height/Width to the Window Height/Width. There are a dozen ways to do it, just get it to fill your entire Window. Give the rectangle a fill color of White and an Opacity of 0. It does need a Fill color to work however with Opacity=0 the user will not see it. For debugging purposes you might give it Red and Opacity .25.

<Rectangle x:Name="fullScreenOverlay" Grid.RowSpan="3" Opacity="0" Fill="White" Visibility="Collapsed" MouseDown="FullScreenOverlay_OnMouseDown" />

这方面的一个关键部分是把矩形在你的XAML的,这样它呈现在其他任何XAML控制之上。

A key part of this is to put the Rectangle at the bottom of your XAML so that it renders on top of any other XAML controls.

当你打开你的组合框状的控制,设置此矩形可见,以便它可以检测的点击/的MouseDown。

When you open your ComboBox like control, set this rectangle to Visible so that it can detect clicks/MouseDown.

private void NotificationButton_Click(object sender, RoutedEventArgs e)
{
    fullScreenOverlay.Visibility = Visibility.Visible;
    notificationPopup.Visibility = Visibility.Visible;
}

当你发现一个点击,设置矩形回倒塌和关闭组合框像弹出。全部完成。

When you detect a click, set the Rectangle back to collapsed and close your ComboBox like popup. All done.

private void FullScreenOverlay_OnMouseDown(object sender, MouseButtonEventArgs e)
{
    fullScreenOverlay.Visibility = Visibility.Collapsed;
    notificationPopup.Visibility = Visibility.Collapsed;
}

这将无法检测到出现应用程序之外的微软组合框不会点击。它只会在应用程序中检测到的点击。但坦率地说,我preFER这种方式呢。

This will not detect clicks that occur outside of your application as the Microsoft ComboBox does. It will only detect clicks inside the application. But frankly, I prefer it that way anyway.

这篇关于WPF - 如何组合框知道什么时候关闭下拉菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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