我有一个包含Popup的Control.我试图在有人点击控件外部时关闭Popup.这是我的代码中设置问题的部分:
AddHandler(Mouse.PreviewMouseDownOutsideCapturedElementEvent,new MouseuttonEventHandler(HandleOutsideClick),true);
现在每当我点击弹出窗口时,它都会引发PreviewMouseDownOutsideCapturedElementEvent.我误解了这个事件吗?是否有一些东西可以让Popup被认为是Control的一部分,这样它就不会引发这个事件?
解决方法
这有用吗?
<Popup Name="Pop" LostFocus="ClosePop"/> private void ClosePop(object sender,RoutedEventArgs e) { Pop.Visibility = Windows.UI.Xaml.Visibility.Collapsed; }
将XAML代码放在.xaml页面中,将C#代码放在相关的.xaml.cs文件中.
注意:在此工作之前,您可能需要将重点放在弹出窗口上,它可能会自动完成;我没有在弹出窗口中这样做,但我已经在其他对象上完成了.
更新:这对我有用,单击TextBox,说明Test1打开Popup,然后单击标记为Test2的TextBox将其关闭:
<Grid Background="White"> <StackPanel> <TextBox Foreground="Black" LostFocus="ClosePop" GotFocus="OpenPop" Height="50">Test1</TextBox> <TextBox Foreground="Black" Height="50">Test2</TextBox> </StackPanel> <Popup Name="Pop" Height="50" Width="50"> <TextBlock Foreground="White" VerticalAlignment="Center" HorizontalAlignment="Center">Pop!</TextBlock> </Popup> </Grid> private void ClosePop(object sender,RoutedEventArgs e) { Pop.IsOpen = false; } private void OpenPop(object sender,RoutedEventArgs e) { Pop.IsOpen = true; }