简体   繁体   中英

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 .

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 .

<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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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