Pass a property to a Label on xamarin

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>
    
asked by anonymous 06.07.2018 / 20:46

1 answer

0

If you are using the MVVM model, add a property in your ViewModel (remembering that your ViewModel should implement the INotifyPropertyChanged interface, 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"); }
     }
}

In 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 the ViewModel to your Binding Context:

public ExemploView(PerfilCadastroViewModel vm)
{
    InitializeComponent();
    BindingContext = new ExemploViewModel();
}
    
09.07.2018 / 17:42