AgentRed
AgentRed

Reputation: 72

Xamarin Forms - How can I "Bind" a string in the code?

i tried doing these

UserInformation.xaml

<StackLayout Orientation="Horizontal" VerticalOptions="Center" HorizontalOptions="Center">
    <Label Text="Name" />
    <Label Text="{Binding  name}"/>
</StackLayout>

Userinformation.xaml.cs

    public async Task GetinfoAsync()
    {

        string name = "Jeremy";

        this.BindingContext = this;

    }

How can i display the variable name in xaml?

Upvotes: 0

Views: 2617

Answers (1)

Babbillumpa
Babbillumpa

Reputation: 1864

You have to use a property for Binding and not a local variable:

class YourViewModel : INotifyPropertyChanged
{
    string name;

    public event PropertyChangedEventHandler PropertyChanged;


    public string Name
    {
        set
        {
            if (name != value)
            {
                name = value;

                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs("Name"));
                }
            }
        }
        get
        {
            return name;
        }
    }
}

Then use the viewmodel class with name property:

public async Task GetinfoAsync()
{
    var vm = new MyViewModel();

    vm.Name = "Jeremy";

    this.BindingContext = vm;

}

The xaml code:

<StackLayout Orientation="Horizontal" VerticalOptions="Center" HorizontalOptions="Center">
    <Label Text="Name" />
    <Label Text="{Binding Name}"/>
</StackLayout>

Upvotes: 2

Related Questions