您可以使用SetBinding()
使用父级(this)作为绑定源时创建绑定。显式指定源参数告诉Binding
将该实例称为Source
.
//<Label Text="{Binding Text, Source={x:Reference this}}" ...
var label = new Label();
label.SetBinding(Label.TextProperty, new Binding(nameof(Text), source: this));
现在设置Style
动态地从资源中获取并不那么简单。当我们使用StaticResource https://github.com/xamarin/Xamarin.Forms/blob/master/Xamarin.Forms.Xaml/MarkupExtensions/StaticResourceExtension.csXAML 中的扩展,它负责沿着视觉树查找匹配的资源(样式)。在代码隐藏中,您必须手动定义确切的资源字典,样式在其中定义。
因此,假设您在 App.xaml 中定义了“LabelText” - 您可以使用以下代码:
//... Style="{StaticResource LabelText}" />
//if the style has been defined in the App resources
var resourceKey = "LabelText";
// resource-dictionary that has the style
var resources = Application.Current.Resources;
if (resources.TryGetValue(resourceKey, out object resource))
label.Style = resource as Style;
如果样式在 PointReductionModeTemplate.xaml 中定义(或ContentView
资源),您也可以使用:
var resources = this.Resources;
if (resources.TryGetValue(resourceKey, out object resource))
label.Style = resource as Style;
最后将标签添加到网格中。
this.ABC.Children.Add(label);