简体   繁体   English

Xamarin Forms 更改框架中的标签文本

[英]Xamarin Forms Change label text in Frame

I have a problem.我有个问题。 I created this frame:我创建了这个框架:

<Frame BackgroundColor="Black" BorderColor="DarkGray" CornerRadius="20" HeightRequest="40" Padding="10,0,10,0">
    <Label Text="{Binding Name}" FontSize="20" TextColor="White" VerticalOptions="CenterAndExpand"
            HorizontalOptions="CenterAndExpand"/>
    <Frame.GestureRecognizers>
        <TapGestureRecognizer Tapped="Category_Clicked" />
    </Frame.GestureRecognizers>
</Frame>

And in the code behind I have this event:在后面的代码中,我有这个事件:

List<string> selectedCategories = new List<string>();
private void Category_Clicked(object sender, EventArgs e)
{
    Frame frame = (Frame)sender;

    if (frame.BackgroundColor == Color.Black)
    {
        frame.BackgroundColor = Color.FromHex("#2196F3");
        //Add label text to list
    }
    else
    {
        frame.BackgroundColor = Color.Black;
        //Remove label text from list
    }
}

But I need to access the text from the label inside the Frame.但我需要从框架内的标签访问文本。 How can I do that?我怎样才能做到这一点?

Get the Label from Content property of Frame .Frame Content属性获取标签。

private void Frame_Tapped(object sender, EventArgs e)
{
    Frame tappedFrame = (sender as Frame);
    Label childLabel = (tappedFrame.Content as Label);
    var resultText = childLabel.Text;
}

Works even if you don't know the type of BindingContext .即使您不知道BindingContext的类型也能工作。

<Frame BackgroundColor="Black" BorderColor="DarkGray" CornerRadius="20" HeightRequest="40" Padding="10,0,10,0">
<Label x:Name = "MyTxt" Text="{Binding Name}" FontSize="20" TextColor="White" VerticalOptions="CenterAndExpand"
        HorizontalOptions="CenterAndExpand"/>
<Frame.GestureRecognizers>
    <TapGestureRecognizer Tapped="Category_Clicked" />
</Frame.GestureRecognizers>

And in Code Behind:在代码隐藏中:

if (frame.BackgroundColor == Color.Black)
{
    frame.BackgroundColor = Color.FromHex("#2196F3");
    //Add label text to list
    MyTxt.text = "Some Text";
}
else
{
    frame.BackgroundColor = Color.Black;
    //Remove label text from list
    MyTxt.text = "";
}

use the BindingContext使用BindingContext

Frame frame = (Frame)sender;
var item = (MyClassName)frame.BindingContext
var name = item.Name;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM