0
votes

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?

3
you are binding to Name, so just use the Name property of your VMJason
But I have multiple names, so multiple framesA. Vreeswijk
You can get the Label inside Frame with Content property. Is pretty straight forward. Correct me if I'm doing it wrong (Any best practice rules I'm missing).Nikhileshwar

3 Answers

0
votes

use the BindingContext

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

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.

1
votes
<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 = "";
}