2
votes

How can I bind a Label in XAML to a public const string in Code Behind using Xamarin.Forms?

Or is there no other way than to create a public static Property that is accessing my public Constant? Which by the way then could be made a private const string instead.

I'm declaring a public const string in my "App" class:

public partial class App : Application
{
    public const string ShortVersion = "v1.00 Beta 1";
    ...

Then I want to bind it to a label in my "MainPage.xaml" file:

<Label Text="{Binding App.ShortVersion}"  
       x:Name="_versionLabel" Style="{StaticResource versionLabel}" ...
/>

It's my first time trying databinding.
Right now I'm doing this (instead of databinding) in my "MainPage.xaml.cs" file:

public MainPage()
{
    InitializeComponent();
    _versionLabel.Text = App.ShortVersion;
}
1
What is your BindingContext? - Mihail Duchev

1 Answers

2
votes

Based on your comment, I see that you are not familiar with how binding works in Xamarin. I strongly suggest that you read thoroughly Data Binding Basics.

Nevertheless, the answer to your question is - yes, you can bind it to a const variable. However, the variable needs to be public.

To sum up how binding works - when you say in your xaml code Text="{Binding App.ShortVersion}", what is happening behind the scenes is:

  1. Xamarin is looking for your BindingContext
  2. If such context is being found, it is being traversed in order to find this property, that you want
  3. If no context is being found, nothing is happening, logically

So, your issue is that you haven't set your BindingContext, meaning that your page/view doesn't know from where to look for this const value. You can have different binding contexts for every page/view/control.

It is a good practice for each page to have its own BindingContext set. This means that you will have MainPageViewModel.cs class. After that, you need to set your page's context to your newly created class like this:

public MainPage()
{
    InitializeComponent();
    BindingContext = new MainPageViewModel();
}

If you absolutely need to have your value in App.xaml.cs file and not in the page's viewModel, in your MainPageViewModel you will have a property, that will be getting its value from the App.ShortVersion.