FindName retornando nulo
Estou escrevendo um simples jogo da velha para a escola. A tarefa é em C ++, mas o professor me deu permissão para usar C # e WPF como um desafio. Eu terminei toda a lógica do jogo e o formulário estava quase completo, mas me deparei com uma parede. Atualmente, estou usando umLabel
para indicar quem é a vez e eu quero alterá-lo quando um jogador faz uma jogada válida. De acordo comAplicações = Código + Marcação, Eu deveria poder usar oFindName
método doWindow
classe. No entanto, ele continua retornandonull
. Aqui está o código:
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";
}
}
Oque esta acontecendo aqui? Estou usando o mesmo nome nos dois lugares, masFindName
não consigo encontrar. Tentei usar o Snoop para ver a hierarquia, mas o formulário não aparece na lista de aplicativos para escolher. Eu procurei no StackOverflow e encontrei Ideve poder usar a classe VisualTreeHelper, mas não entendo como usá-lo.
Alguma ideia?