XAML中的Wpf事件无法正确关注按钮

时间:2013-10-17 07:30:43

标签: c# wpf xaml event-handling windows-controls

当我按下键盘上的箭头键时,我尝试按下按钮。 但我得到的是我总是需要用鼠标按下按钮才能获得正确的焦点,然后我可以用左箭头键移动它,否则不行。但是,正如我所知,KeyDown事件是由Grid而不是按钮触发的。

以下是我在守则背后的做法:

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>

有人可以解释一下吗?感谢。

3 个答案:

答案 0 :(得分:0)

有趣......不确定原因,但如果您想以简单的方式解决它,您可以使用它:

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);
            }
        }
    }
}

(只需将该按钮设置为加载焦点,然后将其移至心脏内容中)。

答案 1 :(得分:0)

没错 - 只有当Grid(Panel)专注于它时,你的KEYDOWN事件才会触发。但是当你的应用程序启动时,它没有专注于它,只有当你选择Grid上的任何控件时才能获得它,例如这个按钮或另一个按钮。 MainWindow专注于start,所以只需将此事件处理程序添加到MainWindow KeyDown。

 <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">
    .....

答案 2 :(得分:0)

这是因为Grid默认情况下无法调焦,因此KeyEventGrid具有焦点或Grid中的某个控件之前无效FocusScope具有逻辑焦点。

您可以将Grid设置为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>