在我的 Silverlight UI 中,我有一个按钮,单击该按钮会弹出一个带有一些过滤参数的控件。我希望此控件在您单击它的外部时隐藏自身。换句话说,它应该以类似于组合框的方式运行,但它不是组合框(您不选择其中的项目)。以下是我如何 try catch 控件外的点击以将其关闭:
public partial class MyPanel : UserControl
{
public MyPanel()
{
InitializeComponent();
}
private void FilterButton_Click(object sender, RoutedEventArgs e)
{
// Toggle the open state of the filter popup
FilterPopup.IsOpen = !FilterPopup.IsOpen;
}
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
// Capture all clicks and close the popup
App.Current.RootVisual.MouseLeftButtonDown += delegate {
FilterPopup.IsOpen = false; };
}
}
不幸的是,MouseLeftButtonDown
的事件处理程序永远不会被触发。是否有一种行之有效的方法来制作当您在其外部单击时自动关闭的弹出控件?如果不是,为什么我的 MouseLeftButtonDown
处理程序没有触发?
解决方案:
我想我会发布我的整个解决方案,以防其他人发现它有帮助。在我的顶级视觉效果中,我为弹出窗口声明了一个“屏蔽”,如下所示:
<UserControl xmlns:my="clr-namespace:Namespace"
x:Class="Namespace.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
xmlns:uriMapper="clr-namespace:System.Windows.Navigation;assembly=System.Windows.Controls.Navigation"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
>
<Grid Background="Black" HorizontalAlignment="Stretch"
VerticalAlignment="Stretch">
<my:MyStuff/>
<Canvas HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
x:Name="PopupShield" Background="Transparent" Width="Auto"
Height="Auto" Visibility="Collapsed"/>
</Grid>
</UserControl>
然后,我为 Popup
类添加了一个扩展方法,如下所示:
public static class PopupUtils
{
public static void MakeAutoDismissing(this Popup popup)
{
var shield = (App.Current.RootVisual as MainPage).PopupShield;
// Whenever the popup opens, deploy the shield
popup.HandlePropertyChanges(
"IsOpen",
(s, e) =>
{
shield.Visibility = (bool)e.NewValue
? Visibility.Visible : Visibility.Collapsed;
}
);
// Whenever the shield is clicked, dismiss the popup
shield.MouseLeftButtonDown += (s, e) => popup.IsOpen = false;
}
}
public static class FrameworkUtils
{
public static void HandlePropertyChanges(
this FrameworkElement element, string propertyName,
PropertyChangedCallback callback)
{
//Bind to a depedency property
Binding b = new Binding(propertyName) { Source = element };
var prop = System.Windows.DependencyProperty.RegisterAttached(
"ListenAttached" + propertyName,
typeof(object),
typeof(UserControl),
new System.Windows.PropertyMetadata(callback));
element.SetBinding(prop, b);
}
}
扩展方法是这样使用的:
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
FilterPopup.MakeAutoDismissing();
}
最佳答案
一种方法是将您的控件放在填充整个 Silverlight 表面的透明 Canvas 上。单击 Canvas 时关闭 Canvas 和控件。如果要接收鼠标事件,请务必确保 Canvas 的背景画笔设置为“透明”。
另一种我没有成功的方法是在 Silverlight 中使用鼠标捕获并检测何时在弹出窗口外单击鼠标。
关于c# - 单击控件外部时如何关闭 Silverlight 中的弹出窗口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2322231/