Skip to content

Instantly share code, notes, and snippets.

@Doprez
Created April 30, 2023 17:26
Show Gist options
  • Save Doprez/169993217a202f0e6e8c2ab93709d85c to your computer and use it in GitHub Desktop.
Save Doprez/169993217a202f0e6e8c2ab93709d85c to your computer and use it in GitHub Desktop.
This is how I create buttons at runtime for a basic inventory system.
public void InitializeOtherInventory()
{
// InventoryPage is a variable assigned through the Stride GameStudion of type UIPage
var inventoryStack = InventoryPage.Page.RootElement.FindVisualChildOfType<ScrollViewer>("OtherItems")
.FindVisualChildOfType<StackPanel>();
// Clear the current list of buttons
inventoryStack.Children.Clear();
// Run GetInventoryButton and add it to the list of reach item
foreach (var item in OtherInventory.Items)
{
string name = $"{item.Name} ({item.Quantity})";
var button = GetInventoryButton(item.ItemPrefab, name, item.Quantity);
inventoryStack.Children.Add(button);
}
_transferButton.IsEnabled = true;
_transferButton.Visibility = Visibility.Visible;
}
// Creates a new button that is cloned from CustomButtons which is a unique UIElement from a UILibrary
private Button GetInventoryButton(Prefab prefab, string text, int quantity, string description = "No description", ISpriteProvider image = null)
{
var element = CustomButtons.InstantiateElement<Button>("ImageTextButton");
element.FindVisualChildOfType<Grid>().FindVisualChildOfType<TextBlock>().Text = text;
if(image != null)
{
element.FindVisualChildOfType<Grid>().FindVisualChildOfType<ImageElement>().Source = image;
}
element.Height = 80;
element.VerticalAlignment = VerticalAlignment.Top;
// add the inventory item to a dictionary and conatin the dictionary key in the button
element.Name = Guid.NewGuid().ToString();
itemsAttachedToButtons.TryAdd(element.Name, prefab);
element.Click += (s, e) => { OnButtonPress(text, description, quantity, image); };
element.Click += ItemButton_Click;
return element;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment