我正在尝试创建一个热键(即 Ctrl + Y),将焦点更改为文本框。
我是从 Delphi 移植过来的,这让我很困惑。在 Delphi 5 中,这非常非常简单。 (在标签的标题上,您只需在要设为热键的字母前添加 & 即可。将标签指向文本框后,热键即可工作。) 对于 WPF,我在 WPF 中看到了可怕的示例,涉及调用 Win32 调用或为每个热键(以及其他此类繁重的实现)发出命令。
我很难相信
1999(Delphi 5)中新推出的 IDE 和 Languange 版本对于像热键这样简单的事情有更好的系统(比 WPF)。 我肯定错过了一些东西。如果你知道请告诉我那是什么。
这样做的方法是创建一个标签并设置其内容(类似这样
Content="_Years Of Service"
)
然后将标签的目标绑定到文本框。 (
Target="{Binding ElementName=SomeTextBox}"
)
现在,如果您按 Alt + Y,它将把焦点移动到 SomeTextBox。
以下是完整装订:
<Label Content="_Label" Target="{Binding ElementName=SomeTextBox}" />
<TextBox Name="SomeTextBox" />
在 XAML 中将下划线 _ 放在要作为热键的字母前面。
方法2:
使用代码隐藏,您必须使用
AccessText
控件,因为它负责在助记符下显示下划线(表示访问键或热键)并识别热键。
注意: 有时 HotKey 下的下划线是不可见的,直到您按下 ALT
键
<Window x:Class="EmptyWPFApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="450" Width="800">
<Grid >
<StackPanel>
<Label Content="_Area" Target="{Binding ElementName=T1}"/>
<TextBox Name="T1">Press ALT+A to get focus</TextBox>
<Label Content="A_bout" Target="{Binding ElementName=T2}"/>
<TextBox Name="T2">Press ALT+B to get focus</TextBox>
<Label x:Name="Label3" Target="{Binding ElementName=T3}"/>
<TextBox x:Name="T3">Press ALT+C to get focus</TextBox>
</StackPanel>
</Grid>
</Window>
MainWindow.xaml.cs
using System.Windows;
using System.Windows.Controls;
namespace EmptyWPFApp
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Label3.Content = new AccessText { Text = "Atta_ck" };
}
}
}