WPF弹出窗口没有按预期工作。因此,当鼠标进入"测试:"按钮时,行为是显示弹出窗口,然后单击弹出窗口上的"关闭"按钮将隐藏弹出窗口。在我左键单击"测试"按钮之前,一切都很好。之后,鼠标事件事件在"测试"按键上启动,但弹出窗口不会显示。
如果有人能在这里帮我,那就太好了。
谢谢,代码
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid Margin="10">
<Button x:Name="btnTest" Width="100" Height="25"
MouseEnter="btnTest_MouseEnter">Test Button</Button>
<Popup Name="MyPopup"
PlacementTarget="{Binding ElementName=btnTest}"
Placement="Mouse"
StaysOpen="False">
<StackPanel Background="PaleGreen">
<Label HorizontalAlignment="Center">I am a popup</Label>
<Button Click="Hide_Click" Content="Close"/>
</StackPanel>
</Popup>
</Grid>
</Grid>
背后的代码
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Input;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Show_Click(object sender, RoutedEventArgs e)
{
MyPopup.IsOpen = true;
}
private void Hide_Click(object sender, RoutedEventArgs e)
{
MyPopup.IsOpen = false;
}
private void btnTest_MouseEnter(object sender, MouseEventArgs e)
{
MyPopup.IsOpen = true;
}
}
}
我试过你的代码,但我不明白为什么它能工作。然而,我尝试用触发器等实现您想要的功能。我已经测试过了,它似乎有效:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid Margin="10">
<Button x:Name="btnTest" Width="100" Height="25" Content="Test Button">
<Button.Triggers>
<EventTrigger RoutedEvent="Button.MouseEnter">
<BeginStoryboard>
<Storyboard>
<BooleanAnimationUsingKeyFrames
Storyboard.TargetName="MyPopup"
Storyboard.TargetProperty="IsOpen"
Duration="0:0:1" FillBehavior="HoldEnd">
<DiscreteBooleanKeyFrame Value="True" KeyTime="0:0:0" />
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Button.Triggers>
</Button>
<Popup Name="MyPopup"
PlacementTarget="{Binding ElementName=btnTest}"
Placement="Mouse"
StaysOpen="False">
<StackPanel Background="PaleGreen">
<Label HorizontalAlignment="Center">I am a popup</Label>
<Button Content="Close">
<Button.Triggers>
<EventTrigger RoutedEvent="Button.Click">
<BeginStoryboard>
<Storyboard>
<BooleanAnimationUsingKeyFrames
Storyboard.TargetName="MyPopup"
Storyboard.TargetProperty="IsOpen"
Duration="0:0:1" FillBehavior="HoldEnd">
<DiscreteBooleanKeyFrame Value="False" KeyTime="0:0:0" />
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Button.Triggers>
</Button>
</StackPanel>
</Popup>
</Grid>
</Grid>
</Window>
我不确定是否有更短的路;可能有。