gpt4 book ai didi

c# - WPF 保持键盘焦点

转载 作者:太空狗 更新时间:2023-10-30 00:47:30 27 4
gpt4 key购买 nike

我正在创建一个 UserControl,它由一个 TextBox 和一个 ListView 组成。只要控件具有键盘焦点,我希望键盘焦点保留在 TextBox 上(ListView 中的选择更改不应从 TextBox< 中删除键盘焦点)。

我尝试在 ListView 中捕获 GotKeyboardFocus 并使用 Keyboard.Focus() 将键盘焦点传回 TextBox , 但这似乎取消了 ListView 中的任何选择操作。下面的代码显示了问题。有谁知道如何实现这个功能?

<Window x:Class="WpfApplication5.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<StackPanel>
<TextBox x:Name="TextBox1" />
<ListView x:Name="ListBox1" Keyboard.GotKeyboardFocus="ListBox1_GotKeyboardFocus">
<ListViewItem Content="Able" />
<ListViewItem Content="Baker" />
<ListViewItem Content="Charlie" />
</ListView>
</StackPanel>
</Window>

using System.Windows;
using System.Windows.Input;

namespace WpfApplication5
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}

private void ListBox1_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
Keyboard.Focus(TextBox1);
}
}
}

最佳答案

相反,您是否考虑过只捕获击键并将这些击键放入您的 TextBox 中?

<Window PreviewKeyDown="Window_PreviewKeyDown" >
<Grid>
<TextBox x:Name="TextBox1" />
<ListBox />
</Grid>
</Window>

然后在您窗口的代码隐藏中:

private void Window_PreviewKeyDown(object sender, KeyEventArgs e)
{
TextBox1.Text += e.Key.ToString();
}

您必须为特殊字符(退格键等)做额外的工作,显然还有用于“Enter”或“Post”操作的 Key 处理程序,但它使您能够自由输入当 Window 具有焦点并根据需要正确处理击键时。

关于c# - WPF 保持键盘焦点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/512902/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com