我在 wpf 中制作了一个用户控制数字键盘。我想知道我何时对表单进行了控制。当我按下任何数字按钮时,它应该被输入到聚焦区域。怎么做
这是我的xaml脚本
enter code here
<RowDefinition Height="1*"/>
<RowDefinition Height="1*"/>
<RowDefinition Height="1*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="1*"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Button Name="btn2" Content="2" Focusable="False" FontSize="26" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Column="1" Grid.Row=" 1" />
<Button Name="btn1" Content="1" Focusable="False" FontSize="26" HorizontalAlignment="Stretch" Grid.Row="1" VerticalAlignment="Stretch" BorderBrush="DarkGray" BorderThickness="4,2,2,8" />
<Button Name="btn3" Content="3" Focusable="False" FontSize="26" Grid.Column="2" Foreground="White" HorizontalAlignment="Stretch" Grid.Row="1" VerticalAlignment="Stretch" />
<Button Name="btn4" Content="4" Focusable="False" FontSize="26" HorizontalAlignment="Stretch" Grid.Row="2" VerticalAlignment="Stretch" />
<Button Name="btn5" Content="5" Focusable="False" FontSize="26" Grid.Column="1" HorizontalAlignment="Stretch" Grid.Row="2" VerticalAlignment="Stretch" />
<Button Name="btn6" Content="6" Focusable="False" FontSize="26" Grid.Column="2" HorizontalAlignment="Stretch" Grid.Row="2" VerticalAlignment="Stretch" />
<Button Name="btn7" Content="7" Focusable="False" FontSize="26" HorizontalAlignment="Stretch" Grid.Row="3" VerticalAlignment="Stretch" />
<Button Name="btn8" Content="8" Focusable="False" FontSize="26" Grid.Column="1" HorizontalAlignment="Stretch" Grid.Row="3" VerticalAlignment="Stretch" />
<Button Name="btn9" Content="9" Focusable="False" FontSize="26" Grid.Column="2" HorizontalAlignment="Stretch" Grid.Row="3" VerticalAlignment="Stretch" />
<Button Name="btn0" Content="0" Focusable="False" FontSize="26" HorizontalAlignment="Stretch" Grid.Row="4" VerticalAlignment="Stretch" />
<Button Name="btn00" Content="00" Focusable="False" FontSize="26" Grid.Column="1" HorizontalAlignment="Stretch" Grid.Row="4" VerticalAlignment="Stretch" />
<Button Name="btn_dot" Content="." Focusable="False" FontSize="26" Grid.Column="2" HorizontalAlignment="Stretch" Grid.Row="4" VerticalAlignment="Stretch" />
<Button Name="btn_temp1" Content="Button" Focusable="False" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
<Button Name="btn_temp2" Content="Button" Focusable="False" Grid.Column="1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
<Button Name="btn_temp3" Content="Button" Focusable="False" Grid.Column="2" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
</Grid>
``
答案 0 :(得分:1)
您应该将事件处理程序附加到UIElement.PreviewKeyDown
Event,以便在UserControl
构造函数或Loaded
事件处理程序中处理WPF中的按键操作:
PreviewKeyDown += YourKeyEventHandler;
...
private void YourKeyEventHandler(object sender, KeyEventArgs e)
{
// Do something here with e.Key (the pressed key)
}
您可以在MSDN上的链接页面中找到更多信息。