如何在Xamarin Form中通过代码向现有Grid动态添加按钮、标签等控件
Hey there! I totally get being a new Xamarin.Forms developer and struggling with dynamic control creation—let's break this down step by step so you can add buttons, labels, custom controls, and more to your existing Grid from code-behind.
Step 1: Clean Up Your XAML
First, remove the static buttons from your Grid in XAML since we'll be adding them dynamically. Your simplified XAML will look like this:
<?xml version="1.0" encoding="utf-8" ?> <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:Status="clr-namespace:SourceCode.Mobile.UI.StatusDetails" x:Class="SourceCode.Mobile.UI.ConsumableScreen"> <ContentPage.Content> <Grid x:Name="MainGrid" Padding="0" Margin="0,0,0,0" RowSpacing="1" ColumnSpacing="1" BackgroundColor="White"> <Grid.ColumnDefinitions> <ColumnDefinition Width="*"></ColumnDefinition> <ColumnDefinition Width="*"></ColumnDefinition> <ColumnDefinition Width="*"></ColumnDefinition> </Grid.ColumnDefinitions> <!-- No static controls here anymore—we'll add them via code! --> </Grid> </ContentPage.Content> </ContentPage>
Step 2: Dynamically Add Controls in Code-Behind
Now let's write the code to create and add controls to your MainGrid. We'll start with the buttons you had, then show how to add labels and custom controls too.
Example 1: Add Buttons
In your ConsumableScreen constructor (or a separate method if you want to trigger it on demand), create each button, set its properties, assign grid positions, attach click events, and add it to the Grid's Children collection:
using System; using Xamarin.Forms; using Xamarin.Forms.Xaml; using SourceCode.Mobile.UI.StatusDetails; // Don't forget to include your custom control namespace namespace SourceCode.Mobile.UI { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class ConsumableScreen : ContentPage { public ConsumableScreen() { InitializeComponent(); AddDynamicControls(); // Call our method to add controls } private void AddDynamicControls() { // Add Device A Button var deviceAButton = new Button { Text = "Device A", WidthRequest = 150, HeightRequest = 50, HorizontalOptions = LayoutOptions.Center, VerticalOptions = LayoutOptions.Center, BackgroundColor = Color.White }; Grid.SetRow(deviceAButton, 0); // Place in row 0 Grid.SetColumn(deviceAButton, 0); // Place in column 0 deviceAButton.Clicked += Button_1_Clicked; // Attach click event MainGrid.Children.Add(deviceAButton); // Add to Grid // Add Device B Button var deviceBButton = new Button { Text = "Device B", WidthRequest = 150, HeightRequest = 50, HorizontalOptions = LayoutOptions.Center, VerticalOptions = LayoutOptions.Center, BackgroundColor = Color.White }; Grid.SetRow(deviceBButton, 0); Grid.SetColumn(deviceBButton, 1); deviceBButton.Clicked += Button_2_Clicked; MainGrid.Children.Add(deviceBButton); // Add Device C Button var deviceCButton = new Button { Text = "Device C", WidthRequest = 150, HeightRequest = 50, HorizontalOptions = LayoutOptions.Center, VerticalOptions = LayoutOptions.Center, BackgroundColor = Color.White }; Grid.SetRow(deviceCButton, 0); Grid.SetColumn(deviceCButton, 2); deviceCButton.Clicked += Button_3_Clicked; MainGrid.Children.Add(deviceCButton); } // Your existing click event handlers private void Button_1_Clicked(object sender, EventArgs e) { // Handle Device A click DisplayAlert("Info", "Device A clicked!", "OK"); } private void Button_2_Clicked(object sender, EventArgs e) { // Handle Device B click DisplayAlert("Info", "Device B clicked!", "OK"); } private void Button_3_Clicked(object sender, EventArgs e) { // Handle Device C click DisplayAlert("Info", "Device C clicked!", "OK"); } } }
Example 2: Add a Label
Want to add a Label? It's almost the same process—just create a Label, set its properties, assign grid position, and add it to the Grid. We'll even add a new row for it:
// Add a new row to the Grid first (if needed) MainGrid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); // Create and add the Label var statusLabel = new Label { Text = "All Devices Online", HorizontalOptions = LayoutOptions.Center, VerticalOptions = LayoutOptions.Center, TextColor = Color.Green, FontSize = 16 }; Grid.SetRow(statusLabel, 1); // Place in the new row (row 1) Grid.SetColumnSpan(statusLabel, 3); // Make it span all 3 columns MainGrid.Children.Add(statusLabel);
Example 3: Add a Custom Control
For your custom control from the Status namespace, follow the same pattern:
// Add another row if needed MainGrid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); // Create your custom control var customStatusControl = new Status.MyCustomControl(); // Replace with your actual control name Grid.SetRow(customStatusControl, 2); Grid.SetColumn(customStatusControl, 0); Grid.SetColumnSpan(customStatusControl, 3); MainGrid.Children.Add(customStatusControl);
Key Notes
- Grid Positioning: Use
Grid.SetRow(control, rowIndex)andGrid.SetColumn(control, columnIndex)to place controls in specific cells. - Row/Column Spanning: Use
Grid.SetRowSpanorGrid.SetColumnSpanto make controls span multiple rows/columns. - Dynamic Rows/Columns: If you need more rows or columns than defined in XAML, add new
RowDefinitionorColumnDefinitionobjects toMainGrid.RowDefinitionsorMainGrid.ColumnDefinitions. - Event Handling: Attach events (like
Clickedfor buttons) just like you would with static controls.
That's it! You can now dynamically add any control to your Grid whenever you need—whether it's on page load, in response to a user action, or from data fetched at runtime.
内容的提问来源于stack exchange,提问作者skt

