gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 13:43:41 24 4
gpt4 key购买 nike

我有这个模板:

<?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}" />

最佳答案

您可以使用 SetBinding() 创建绑定(bind),同时使用父级 (this) 作为绑定(bind)源。显式指定 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));

现在从资源中动态设置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;

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

var resources = this.Resources;
if (resources.TryGetValue(resourceKey, out object resource))
label.Style = resource as Style;

最后将标签添加到网格。

this.ABC.Children.Add(label);

关于c# - 如何将 C# 中的标签添加到我的 XAML 代码中的网格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52456194/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com