我在XAML中创建了几个条目和按钮(还没有C#代码)。 是否可以编辑甚至将C#代码中的元素添加到在XAML中创建的StackLayout中?
例如,拥有以下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:local="clr-namespace:ORTEC_MOBILE"
x:Class="ORTEC_MOBILE.MainPage"
BackgroundColor="#0074ff">
<RelativeLayout>
<StackLayout HorizontalOptions="FillAndExpand"
RelativeLayout.YConstraint="{ConstraintExpression Type=RelativeToParent, Property=Height, Factor=0.25,Constant=0}"
RelativeLayout.WidthConstraint="{ConstraintExpression Type=RelativeToParent, Property=Width,Factor=1,Constant=0}">
<Label Text="Login" FontSize="36" TextColor="White" HorizontalTextAlignment="Center">
</Label>
<Label Text="Welcome back! Please log into your account." FontSize="12" TextColor="White" HorizontalTextAlignment="Center">
</Label>
</StackLayout>
</RelativeLayout>
是否可以使用C#代码向布局添加按钮?
答案 0 :(得分:2)
是的,绝对有可能。当您为元素提供netty-all
属性时,它在代码隐藏中可用作“元素”。在Xamarin网站上查看此示例,了解它们如何在代码中调用元素:
https://github.com/xamarin/xamarin-forms-book-samples/tree/master/Chapter08/XamlClock
x:Name="element"
属性允许为在XAML中实例化的对象指定名称。这些名称的规则与C#变量名称的规则相同。在构造函数中返回x:Name
调用之后,代码隐藏文件可以引用这些名称来访问相应的XAML元素。这些名称实际上是由XAML解析器转换为生成的分部类中的私有字段。
答案 1 :(得分:1)
绝对可以从后面的代码中以编程方式添加控件,我将在下面给出一个示例。
将您希望添加控件的组件添加到名称中可能很有用,这样就可以从xaml后面的类中访问它。
因此,在这种情况下,我只是将一个名称归因于您的xaml堆栈布局。
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:local="clr-namespace:ORTEC_MOBILE"
x:Class="ORTEC_MOBILE.MainPage"
BackgroundColor="#0074ff">
<RelativeLayout>
<StackLayout x:Name="mainStackLayout" HorizontalOptions="FillAndExpand"
RelativeLayout.YConstraint="{ConstraintExpression Type=RelativeToParent, Property=Height, Factor=0.25,Constant=0}"
RelativeLayout.WidthConstraint="{ConstraintExpression Type=RelativeToParent, Property=Width,Factor=1,Constant=0}">
<Label Text="Login" FontSize="36" TextColor="White" HorizontalTextAlignment="Center">
</Label>
<Label Text="Welcome back! Please log into your account." FontSize="12" TextColor="White" HorizontalTextAlignment="Center">
</Label>
</StackLayout>
</RelativeLayout>
C#Backing Class:
Public void SomeMethodThatsInMyBackingClass()
{
Label newLabel = new Label {
Text = "Hello, Forms!",
FontSize = Device.GetNamedSize (NamedSize.Large, typeof(Label)),
VerticalOptions = LayoutOptions.CenterAndExpand,
HorizontalOptions = LayoutOptions.CenterAndExpand,
},
mainStackLayout.Children.Add(newLabel);
}
使用上面的粗略示例应该足以让您在自己的项目中复制它。祝你好运。