I am trying to change some elements of my WPF page after pressing the right and left keys on my keyboard. It works somewhat fine, my problem is that I need to press the right or left keys 3 times each time I want something to change. Also, I don’t know if it’s relevant but a weird rectangle appears after pressing the key for the first time, but if I press it again it disappears.
XAML code
<Page x:Class="PokemonGroveGreen.Bag"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:PokemonGroveGreen"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800"
Title="Bag">
<Viewbox x:Name="mainViewbox" Stretch="Fill" StretchDirection="Both" Focusable="True" KeyDown="Viewbox_KeyDown">
<Grid>
<!-- Background -->
<Image Source="/Images/bagBackground.png"></Image>
<!-- Pocket symbols -->
<Grid Height="43" Width="338" Margin="25,348,621,347">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<!-- Items -->
<Border Grid.Column="0" BorderBrush="Red" BorderThickness="0"/>
<!-- Medicine -->
<Border Grid.Column="1" BorderBrush="Red" BorderThickness="0"/>
<!-- Poké Balls -->
<Border Grid.Column="2" BorderBrush="Red" BorderThickness="0"/>
<!-- TMs & HMs -->
<Border Grid.Column="3" BorderBrush="Red" BorderThickness="0"/>
<!-- Berries -->
<Border Grid.Column="4" BorderBrush="Red" BorderThickness="0"/>
<!-- Treasures -->
<Border Grid.Column="5" BorderBrush="Red" BorderThickness="0"/>
<!-- Battle Items -->
<Border Grid.Column="6" BorderBrush="Red" BorderThickness="0"/>
<!-- Key Items -->
<Border Grid.Column="7" BorderBrush="Red" BorderThickness="0"/>
</Grid>
<!-- Pocket text -->
<TextBlock x:Name="pocketBlock" Text="Items" Height="50" Width="350" FontSize="40" TextAlignment="Center" Margin="18,413,616,275"></TextBlock>
</Grid>
</Viewbox>
</Page>
XAML.CS
namespace PokemonGroveGreen
{
/// <summary>
/// Lógica de interacción para Bag.xaml
/// </summary>
public partial class Bag : Page
{
Trainer trainer;
public Bag(Trainer trainer)
{
InitializeComponent();
mainViewbox.Focus();
this.trainer = trainer;
}
private void Viewbox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Right)
{
pocketBlock.Text = "DERECHA";
}
else if (e.Key == Key.Left)
{
pocketBlock.Text = "IZQUIERDA";
}
}
}
}
screenshot of the rectangle
I tried changing the event to the page, the grid and the viewbox. I also tried using the KeyDown event and the PreviewKeyDown event. Both worked the same way.