我是Xamarin Form的新手。我的要求是。我想基于现有的Grid(如下代码)根据需要动态添加按钮或自定义按钮或标签等(后面的代码)(如下面的代码)。但是我不知道在现有的Grid上添加项目的方式。我已经尝试了很多,但没有找到任何样本。

我的XAML代码如下。

<?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>

            <!--   These below button should be from code behind dynamically -->

            <Button  Grid.Row="0" Grid.Column="0" Text="Device A" WidthRequest="150" HeightRequest="50" HorizontalOptions="Center" VerticalOptions="Center" BackgroundColor="White" Clicked="Button_1_Clicked"></Button>
            <Button  Grid.Row="0" Grid.Column="1" Text="Device B" WidthRequest="150" HeightRequest="50" HorizontalOptions="Center" VerticalOptions="Center" BackgroundColor="White" Clicked="Button_2_Clicked"></Button>
            <Button  Grid.Row="0" Grid.Column="2" Text="Device C" WidthRequest="150" HeightRequest="50" HorizontalOptions="Center" VerticalOptions="Center" BackgroundColor="White" Clicked="Button_3_Clicked"></Button>
        </Grid>

    </ContentPage.Content>
</ContentPage>


后面的代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace SourceCode.Mobile.UI
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class ConsumableScreen : ContentPage
    {

        public ConsumableScreen( )
        {
            InitializeComponent();
        }

    }
}


任何人都可以帮助我如何从后面的代码在Button的现有单元格上创建Label或任何其他控件,例如TextBoxGrid等。

提前致谢。

苏舍尔

最佳答案

尝试这个:

Button button = new Button();
button.Text = "Device B";
button.Clicked = Button_2_Clicked;
button.WidthRequest = 150.0;
button.HeightRequest = 50.0;
button.HorizontalOptions = Xamarin.Forms.LayoutOptions.Center;
button.VerticalOptions = Xamarin.Forms.LayoutOptions.Center;
button.Color = Xamarin.Forms.Color.White;
Grid.SetRow(button, 0);
Grid.SetColumn(button, 1);
MainGrid.Children.Add(button);

关于c# - 如何使用Xamarin Form以编程方式在现有网格上添加按钮或标签?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50366910/

10-12 00:19
查看更多