0

当使用 DispatcherTimer 在某个时间按下按钮时,我会打开一个弹出窗口。这工作正常,但即使 StaysOpen 属性设置为 false,弹出窗口也会保持打开状态。这是代码:

XAML:

<Grid>
    <Button x:Name="_button" Content="open" PreviewMouseDown="Button_PreviewMouseDown" PreviewMouseUp="Button_PreviewMouseUp" Width="100" Height="50"/>
    <Popup x:Name="_popup" StaysOpen="False" Width="300" Height="300"/>
</Grid>

代码背后:

public partial class MainWindow : Window {

    private DispatcherTimer _dispatcherTimer;

    public MainWindow() {
        InitializeComponent();
    }

    private void Button_PreviewMouseUp(object sender, MouseButtonEventArgs e) {
        _dispatcherTimer.Stop();
    }

    private void DispatcherTimer_Tick(object sender, EventArgs e) {
        _dispatcherTimer.Stop();
        _popup.IsOpen = true;
    }

    private void Button_PreviewMouseDown(object sender, MouseButtonEventArgs e) {
        _dispatcherTimer = new DispatcherTimer();
        _dispatcherTimer.Tick += new EventHandler(DispatcherTimer_Tick);
        _dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 800);
        _dispatcherTimer.Start();
    }

}

如果我在没有 DispatcherTimer 的情况下打开弹出窗口,一切都会按我的预期工作。我的问题是:

  • 为什么使用 DispatcherTimer 打开弹出窗口时会出现这样的行为?
  • 是否有一些解决方法可以使这项工作?(在弹出窗口外单击时弹出窗口会自动关闭)

谢谢!

4

0 回答 0