如何在我的XAML代码中使用C#向网格添加标签?

3

我有这个模板:

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

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

<Label Text="{Binding Text, Source={x:Reference this}}" Style="{StaticResource LabelText}" />

你想使用C#还是XAML来完成呢? - R15
3个回答

5
你可以使用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 不是一件容易的事情。当我们在 XAML 中使用 StaticResource 扩展时,它会负责向上遍历可视树来查找匹配的资源(样式)。在代码后台中,您必须手动定义确切的资源字典,其中定义了样式。
所以假设您已经在 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);

3
您需要创建一个Label类的对象,然后将该对象添加到您的网格的Children属性中。
Label dynamicLabel = new Label();

dynamicLabel.Name = "NewLabel";
dynamicLabel.Content = "TEST";
dynamicLabel.Width = 240;
dynamicLabel.Height = 30;
dynamicLabel.Margin = new Thickness(0, 21, 0, 0);
dynamicLabel.Foreground = new SolidColorBrush(Colors.White);
dynamicLabel.Background = new SolidColorBrush(Colors.Black);

Grid.SetRow(dynamicLabel, 1);
Grid.SetColumn(dynamicLabel, 0);

gride.Children.Add(dynamicLabel);

1
谢谢,但如果您的答案更贴近问题而不是简单复制粘贴的话会更好。 - Alan2

1
您可以尝试这个:

你可以试试这个

Grid grid = new Grid();
grid.SetBinding(Grid.BindingContextProperty, "Source");

Label label = new Label();
label.SetBinding(Label.TextProperty,FieldName);
Resources.Add ("label", customButtonStyle);
grid.Children.Add(label)

Grid中添加Label,请指定您喜欢的位置。以下是在程序中设置Label绑定的示例代码。
label.BindingContext = list; // The observablecollection
label.SetBinding(Label.TextProperty, "Count");

以编程方式设置样式以编程方式绑定

希望它能帮助你。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接