Pass a property to a Label on Xamarin

Asked

Viewed 94 times

0

I need to make the label of my code receive the value of a property.

<Grid BackgroundColor="Black">
        <Grid.ColumnDefinitions>
            <ColumnDefinition></ColumnDefinition>
            <ColumnDefinition></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>            
        </Grid.RowDefinitions>
        <Label Grid.Column="0" Grid.Row="0"
               Text="Ponto" 
               FontSize="20" TextColor="WhiteSmoke"               
               VerticalTextAlignment="Center" HorizontalTextAlignment="Center"></Label>
        <Label Grid.Column="1" Grid.Row="0"
               Text="Ponto" TextColor="WhiteSmoke" FontSize="20"
               VerticalTextAlignment="Center" HorizontalTextAlignment="Center"></Label>
        <Button Grid.Column="0" Grid.Row="1"
                Text="+1" TextColor="WhiteSmoke" FontSize="20"
                BackgroundColor="OrangeRed"></Button>
        <Button Grid.Column="1" Grid.Row="1"
                Text="+1" TextColor="WhiteSmoke" FontSize="20"
                BackgroundColor="OrangeRed"></Button>
        <Button Grid.Column="0" Grid.Row="2"
                Text="-1" TextColor="WhiteSmoke" FontSize="20"
                BackgroundColor="OrangeRed"></Button>
        <Button Grid.Column="1" Grid.Row="2"
                Text="-1" TextColor="WhiteSmoke" FontSize="20"
                BackgroundColor="OrangeRed"></Button>
 </Grid>
  • 1

    You are using the MVVM model?

1 answer

0

If you are using the MVVM model, add a property to your Viewmodel (remembering that your Viewmodel should implement the interface Inotifypropertychanged, I’ll leave an example).

using System.ComponentModel;
using Xamarin.Forms

public class ExemploViewModel : INotifyPropertyChanged
{
     public void OnPropertyChanged([CallerMemberName()]string name = null)
     {
         PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
     }

     private string _titulo;
     public string Titulo
     {
        get { return _titulo; }
        set { _titulo = value; OnPropertyChanged("Titulo"); }
     }
}

On your Label do the Binding with the property.

<Label Grid.Column="0" Grid.Row="0"
       Text="{Binding Titulo}" 
       FontSize="20" 
       TextColor="WhiteSmoke"               
       VerticalTextAlignment="Center" 
       HorizontalTextAlignment="Center">

In the code Behind (xaml.Cs) of your page, assign Viewmodel to your Binding Context:

public ExemploView(PerfilCadastroViewModel vm)
{
    InitializeComponent();
    BindingContext = new ExemploViewModel();
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.