I am making Tetris using WPF C# and currently I am able to hold a piece and store the held piece in a stack. The problem I am having right now is with being able to give a preview of the held piece on the UI. I am unsure on how I am meant to bind the images corresponding to the held piece to the UI. I have already implemented the Top() function allowing me to see the held piece in the stack, I just don’t know how to represent this with the image.
private void holdTetromino()
{
if (canHold == true)
{
if (holdStack.isEmpty() == true)
{
holdStack.Push(currentTetromino.index);
SpawnNewTetromino(pieceQueue.Dequeue());
}
else
{
int temp = holdStack.Pop();
holdStack.Push(currentTetromino.index);
SpawnNewTetromino(temp);
}
canHold = false;
}
}
public string holdImgUri()
{
string uri = "";
switch (holdStack.Top())
{
case 0:
uri = @"C:Usersbish2sourcereposNEATetrisotetrominoPNGtetrominoI.PNG";
break;
case 1:
uri = @"C:Usersbish2sourcereposNEATetrisotetrominoPNGtetrominoO.PNG";
break;
case 2:
uri = @"C:Usersbish2sourcereposNEATetrisotetrominoPNGtetrominoL.png";
break;
case 3:
uri = @"C:Usersbish2sourcereposNEATetrisotetrominoPNGtetrominoJ.PNG";
break;
case 4:
uri = @"C:Usersbish2sourcereposNEATetrisotetrominoPNGtetrominoT.PNG";
break;
case 5:
uri = @"C:Usersbish2sourcereposNEATetrisotetrominoPNGtetrominoS.PNG";
break;
case 6:
uri = @"C:Usersbish2sourcereposNEATetrisotetrominoPNGtetrominoZ.PNG";
break;
}
return uri;
}
The holdImageUri function is meant to set the uri that is to be used based on what the current held tetromino is.
enter image description here
This is the current image folder I have.
I have tried looking online on how to do One Way data binding and how I can work with images but I have not been able to come up with a solution in the end. To be honest, any help in general on how to successfully bind an image will be helpful for me to figure out how to do it in my case.
Bish is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
0
You need to expose a property that will represent the image URI and ensure it notifies the UI when it changes.
-
Add HeldPieceImageUri as a property with INotifyPropertyChanged to ensure the UI updates when the image changes.
- Use another function UpdateHeldPieceImage() to update HeldPieceImageUri based on the top value of holdStack.
- Finally, call UpdateHeldPieceImage() at the end of holdTetromino().
Don’t forget to update your WPF XAML to include an Image control to preview the held piece. Also make sure the TetrisViewModel is set as the DataContext of your Window.