Gautam Saxena
Gautam Saxena

Reputation: 3

How to use value of a C# variable in XAML in Xamarin.Forms?

I am a newbie in Xamarin.forms as well as in C#, I am creating a user account page with Xaml named userac.xaml, in which there will be a label saying, "Hello, [name of user]" and their is a string variable in userac.xaml.cs which contains the name of user which will be displayed in userac.xaml page as "Hello, [name of user]", but I can't figure out how to do so. Please Help.

I have attached the code:-

    <StackLayout>
        <Label Text=""
            VerticalOptions="CenterAndExpand" 
            HorizontalOptions="CenterAndExpand" />
    </StackLayout>

userac.xaml.cs:-

public partial class userac : ContentPage
{
    public Contracts()
    {
        InitializeComponent();
    }
}

Upvotes: 0

Views: 1765

Answers (1)

Jonathan Applebaum
Jonathan Applebaum

Reputation: 5986

You should use data binding.
Also, as you said you are a newbie to the C# language, so if you are not familiar with C# Properties declaration you can see in the example (the get() and set() methods inside the code) please read this.

Please see comments inside the example based on your code:

.XAML:

 <StackLayout>
          <Label Text="{Binding TheUserName}"
          VerticalOptions="CenterAndExpand" 
          HorizontalOptions="CenterAndExpand" />
  </StackLayout>

.CS:

public partial class userac : ContentPage
{
    private string _TheUserName = "Some User Name";
    public string TheUserName
    {
        get
        {
            return "Hello " + _TheUserName;
        }
        set
        {
            _TheUserName = value;
            // read here about OnPropertyChanged built-in method https://learn.microsoft.com/en-us/dotnet/api/xamarin.forms.bindableobject.onpropertychanged?view=xamarin-forms
            OnPropertyChanged("TheUserName");
        }
    }

    public userac()
    {
        // Note: binding context can also to another view model class of this view, but here we will use the class of this specific view
        // So, you can also do something like that:
        // BindingContext = new useracViewModel() 
        BindingContext = this;
        // you can also change the default value of _TheUserName by getting it from database, xml file etc...
        TheUserName = GetCurrentUserName();

        InitializeComponent();
    }

    private string GetCurrentUserName()
    {
        // ...
        // do things to retrieve the user name...
        // ...
        return "John Doe";
    }
}

Upvotes: 2

Related Questions