如何在我的XAML代码中将C#中的标签添加到网格中?

Ala*_*an2 3 c# xamarin xamarin.forms

我有这个模板:

<?xml version="1.0" encoding="UTF-8"?>
<ContentView xmlns="http://xamarin.com/schemas/2014/forms" 
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
             x:Class="Japanese.Templates.PointReductionModeTemplate" x:Name="this">
    <StackLayout BackgroundColor="#FFFFFF" Padding="20,0" HeightRequest="49" Margin="0">
        <Grid VerticalOptions="CenterAndExpand" x:Name="ABC">

        </Grid>
    </StackLayout>
</ContentView>
Run Code Online (Sandbox Code Playgroud)

如何使用此文本和样式将此标签添加到C#中的Grid?请注意,我希望能够引用Source={x:Reference this}

<Label Text="{Binding Text, Source={x:Reference this}}" Style="{StaticResource LabelText}" />
Run Code Online (Sandbox Code Playgroud)

Sha*_*raj 5

您可以使用SetBinding()parent(this)作为绑定源来创建绑定.显式指定source参数告诉它Binding将该实例引用为Source.

//<Label Text="{Binding Text, Source={x:Reference this}}" ...
var label = new Label();
label.SetBinding(Label.TextProperty, new Binding(nameof(Text), source: this));
Run Code Online (Sandbox Code Playgroud)

现在Style从资源动态设置并不是那么简单.当我们StaticResource在XAML中使用扩展时,它负责走向可视树以找到匹配的资源(样式).在代码隐藏中,您必须手动定义确切的资源字典,其中定义了样式.

因此,假设您在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;
Run Code Online (Sandbox Code Playgroud)

如果样式在PointReductionModeTemplate.xaml(或ContentView资源)中定义,您可以使用:

var resources = this.Resources;
if (resources.TryGetValue(resourceKey, out object resource))
    label.Style = resource as Style;
Run Code Online (Sandbox Code Playgroud)

最后将标签添加到网格中.

this.ABC.Children.Add(label);
Run Code Online (Sandbox Code Playgroud)