C# XAML中的Wpf事件无法在按钮上获得正确的焦点
当我按下键盘上的箭头键时,我试图使按钮移动。 但我得到的是,我总是需要用鼠标按下按钮,首先获得正确的焦点,然后我可以用左箭头键移动它,否则就不行了。然而,据我所知,KeyDown事件是由网格而不是按钮触发的 以下是我在代码隐藏中的操作方式:C# XAML中的Wpf事件无法在按钮上获得正确的焦点,c#,wpf,xaml,event-handling,windows-controls,C#,Wpf,Xaml,Event Handling,Windows Controls,当我按下键盘上的箭头键时,我试图使按钮移动。 但我得到的是,我总是需要用鼠标按下按钮,首先获得正确的焦点,然后我可以用左箭头键移动它,否则就不行了。然而,据我所知,KeyDown事件是由网格而不是按钮触发的 以下是我在代码隐藏中的操作方式: private void Panel_KeyDown(object sender, KeyEventArgs e) { Button source = Baffle; if (source != null) {
private void Panel_KeyDown(object sender, KeyEventArgs e)
{
Button source = Baffle;
if (source != null)
{
if (e.Key == Key.Left)
{
source.Margin = new Thickness(source.Margin.Left - 1, source.Margin.Top,
source.Margin.Right + 1, source.Margin.Bottom);
}
}
}
XAML:
<Grid Name="Panel" KeyDown="Panel_KeyDown" Background="BlanchedAlmond">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Button Name="Baffle" Template="{StaticResource ButtonTemplate}"
Grid.Row="1" VerticalAlignment="Bottom" Margin="20" HorizontalAlignment="Center"
Width="50" Height="20"/>
</Grid>
有人能解释一下吗?谢谢。很有趣。。。不确定原因,但如果您想以简单的方式解决此问题,可以使用以下方法:
public partial class MainWindow : Window
{
private Button source;
public MainWindow()
{
InitializeComponent();
source = Baffle;
source.Focus();
}
private void Panel_KeyDown(object sender, KeyEventArgs e)
{
if (source != null)
{
if (e.Key == Key.Left)
{
source.Margin = new Thickness(source.Margin.Left - 1, source.Margin.Top,
source.Margin.Right + 1, source.Margin.Bottom);
}
}
}
}
只需将焦点放在加载上,您就可以将其移动到心底内容。没错-只有当GridPanel将焦点放在该按钮上时,您的KEYDOWN事件才会触发。但当应用程序启动时,它并没有关注它,只有在您选择网格上的任何控件(例如此按钮或其他按钮)时,它才会得到它。MainWindow的焦点是启动,所以只需将此事件处理程序添加到MainWindow键下
<Window x:Class="WpfApplication4.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" KeyDown="Panel_KeyDown">
<Grid Name="Panel" Background="BlanchedAlmond">
.....
这是因为网格在默认情况下是不可聚焦的,所以在网格具有焦点或网格聚焦范围中的某个控件具有逻辑焦点之前,KeyEvent不会工作
您可以将网格设置为Focusable,并使用FocusManager将FocusedElement设置为网格,这将起作用
例如:
<Grid Name="Panel" KeyDown="Panel_KeyDown" Background="BlanchedAlmond" FocusManager.FocusedElement="{Binding ElementName=Panel}" Focusable="True">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Button Name="Baffle"
Grid.Row="1" VerticalAlignment="Bottom" Margin="20" HorizontalAlignment="Center"
Width="50" Height="20"/>
</Grid>