c# - 只要TextBox具有键盘焦点,就保持弹出窗口处于打开状态并处于事件状态

标签 c# wpf mvvm popup

我有一个弹出窗口,当TextBox具有键盘焦点时,我想一直保持打开状态并激活其内容。我已经尝试过使用此代码

public partial class MyPopup : Popup
{
    public MyPopup
    {
        InitializeComponent();

        EventManager.RegisterClassHandler(
            typeof(UIElement),
            Keyboard.PreviewGotKeyboardFocusEvent,
            (KeyboardFocusChangedEventHandler)OnPreviewGotKeyboardFocus);
    }

    private void OnPreviewGotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
    {
        if (sender is TextBox)
            this.IsOpen = true;
        else
            this.IsOpen = false;
    }
}

我在App的构造函数中创建Popup。

此代码的问题在于,如果使用ShowDialog时已经打开了Popup,则Popup不再处于 Activity 状态,即使它仍在视觉上位于顶部。

如何解决此问题或以其他方式获得所需的行为。

最佳答案

找到了一种解决方案,通过检查窗口是否已加载来检查窗口是否正在打开。如果是这样,我关闭弹出窗口,并在新窗口呈现其内容后再次将其重新打开。

不确定我是否足够信任使用它,因此将欢迎更好的解决方案。

private void OnGotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
    {
        e.Handled = true;
        if (sender is TextBox)
        {
            var _parentWindow = Window.GetWindow((UIElement)sender);
            if (!_parentWindow.IsLoaded)
            {
                this.IsOpen = false;
                _parentWindow.ContentRendered += (o, i) => this.IsOpen = true;
            }
            else
            {
                this.IsOpen = true;
            }
        }
        else
        {
            this.IsOpen = false;
        }
    }

关于c# - 只要TextBox具有键盘焦点,就保持弹出窗口处于打开状态并处于事件状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32254943/

相关文章:

c# - 如何从 C# 关闭计算机

c# - VS2005.net 2.0 c# : Best way to create xml file

.net - WPF TreeView - 使用嵌套集合和 "Static nodes"绑定(bind)到 ViewModel

silverlight - MVVM、动画、绑定(bind)——我需要一个快速的问题回答

wpf - 您如何导航复杂的可视化树以重新绑定(bind)现有元素?

c# - 你怎么知道流是否关闭?

c# - 根据特定列从列表中删除重复行

c# - 在 Listbox 上使用自定义 DataTemplate 时,SelectedItem 绑定(bind)停止工作

c# - WPF 中现有的 Crystal Report

c# - Kinect SDK - 按度数变换角度的旋转