Estoy escribiendo un juego de tic tac toe para la escuela. La tarea está en C++, pero el maestro me ha dado permiso para usar C# y WPF como un desafío. He terminado toda la lógica del juego y la forma está casi completa, pero me he topado con un muro. Actualmente estoy usando un Label
para indicar quién es el turno y quiero cambiarlo cuando un jugador realiza un movimiento válido. De acuerdo con Applications = Code + Markup, debería ser capaz de usar el método FindName
de la clase Window
. Sin embargo, sigue volviendo null
. Aquí está el código:FindName return null
public TicTacToeGame()
{
Title = "TicTacToe";
SizeToContent = SizeToContent.WidthAndHeight;
ResizeMode = ResizeMode.NoResize;
UniformGrid playingField = new UniformGrid();
playingField.Width = 300;
playingField.Height = 300;
playingField.Margin = new Thickness(20);
Label statusDisplay = new Label();
statusDisplay.Content = "X goes first";
statusDisplay.FontSize = 24;
statusDisplay.Name = "StatusDisplay"; // This is the name of the control
statusDisplay.HorizontalAlignment = HorizontalAlignment.Center;
statusDisplay.Margin = new Thickness(20);
StackPanel layout = new StackPanel();
layout.Children.Add(playingField);
layout.Children.Add(statusDisplay);
Content = layout;
for (int i = 0; i < 9; i++)
{
Button currentButton = new Button();
currentButton.Name = "Space" + i.ToString();
currentButton.FontSize = 32;
currentButton.Click += OnPlayLocationClick;
playingField.Children.Add(currentButton);
}
game = new TicTacToe.GameCore();
}
void OnPlayLocationClick(object sender, RoutedEventArgs args)
{
Button clickedButton = args.Source as Button;
int iButtonNumber = Int32.Parse(clickedButton.Name.Substring(5,1));
int iXPosition = iButtonNumber % 3,
iYPosition = iButtonNumber/3;
if (game.MoveIsValid(iXPosition, iYPosition) &&
game.Status() == TicTacToe.GameCore.GameStatus.StillGoing)
{
clickedButton.Content =
game.getCurrentPlayer() == TicTacToe.GameCore.Player.X ? "X" : "O";
game.MakeMoveAndChangeTurns(iXPosition, iYPosition);
// And this is where I'm getting it so I can use it.
Label statusDisplay = FindName("StatusDisplay") as Label;
statusDisplay.Content = "It is " +
(game.getCurrentPlayer() == TicTacToe.GameCore.Player.X ? "X" : "O") +
"'s turn";
}
}
¿Qué está pasando aquí? Estoy usando el mismo nombre en ambos lugares, pero FindName
no puedo encontrarlo. Intenté usar Snoop para ver la jerarquía, pero el formulario no aparece en la lista de aplicaciones para elegir. Busqué en StackOverflow y encontré I should be able to use VisualTreeHelper class, pero no entiendo cómo usarlo.
¿Alguna idea?
Elegí, para este programa, para ir con el miembro privado. Gracias por la explicación, leeré la página completa tan pronto como pueda. –