如何将 C# 中的标签添加到 XAML 代码中的网格? [英] How can I add a label in C# to a grid in my XAML code?
问题描述
我有这个模板:
<?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}
How can I add this label to the Grid in C# with this Text and Style? Note that I want to be able to reference the Source={x:Reference this}
also
<Label Text="{Binding Text, Source={x:Reference this}}" Style="{StaticResource LabelText}" />
推荐答案
您可以使用 SetBinding()
来创建绑定,同时使用 parent (this) 作为绑定源.显式指定源参数告诉 Binding
将该实例引用为 Source
.
You can use SetBinding()
to create the binding while using parent (this) as binding-source. Explicitly specifying the source parameter tells the Binding
to refer that instance as 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
扩展,它负责沿着视觉树向上查找匹配的资源(样式).在代码隐藏中,您必须手动定义确切的资源字典,样式在其中定义.
Now setting the Style
dynamically from resources is not as straightforward. When we use StaticResource
extension in XAML, it takes care of walking up the visual-tree to find the matching resource (style). In code-behind, you will have to manually define the exact resource-dictionary, the style is defined in.
因此假设您在 App.xaml 中定义了LabelText" - 您可以使用以下代码:
So assuming you have the 'LabelText' defined in App.xaml - you can use following code:
//... 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
资源)中定义了样式,您也可以使用:
If the style is defined in PointReductionModeTemplate.xaml (or ContentView
resources), you can alternatively use:
var resources = this.Resources;
if (resources.TryGetValue(resourceKey, out object resource))
label.Style = resource as Style;
最后将标签添加到网格中.
And finally add the label to grid.
this.ABC.Children.Add(label);
这篇关于如何将 C# 中的标签添加到 XAML 代码中的网格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!