簡體   English   中英

如何在我的XAML代碼中將C#中的標簽添加到網格中?

[英]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#中的Grid? 請注意,我希望能夠引用Source={x:Reference this}

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

您可以使用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));

現在從資源動態設置Style並不是那么簡單。 當我們在XAML中使用StaticResource擴展時,它負責走向visual-tree以找到匹配的資源(樣式)。 在代碼隱藏中,您必須手動定義確切的資源字典,其中定義了樣式。

因此,假設您在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);

您應該創建label類的對象,然后將此對象添加到網格的Chidlers屬性中。

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);

你可以試試這個

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");

以編程方式編寫樣式並以編程方式 綁定

希望它對你有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM