Hello,
Welcome to our Microsoft Q&A platform!
How can I bind my XAML to a static variable inside the App.xaml.cs
For this function, try using ResourceDictionary
to store the resources. Then reference and apply the resource to elements by using the StaticResource
or DynamicResource
markup extension.
To Label.Text is type of string
, so please use a string value instead. You could create the resource for 'my_birthday' in code and use DynamicResource
markup extension to apply it.
Check the code:
//App.xaml
<Application xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="TestApplication_5.App">
<Application.Resources>
<x:String x:Key="my_name">MyName</x:String>
</Application.Resources>
</Application>
//App.xaml.cs
public partial class App : Application
{
public App()
{
InitializeComponent();
MainPage = new NavigationPage(new TestPage());
DateTime date = xxx;
Application.Current.Resources.Add("my_birthday", date.ToString());
}
...
}
Consume the resources in the page.xaml.
<StackLayout>
<Label Text="{StaticResource my_name}" />
<Label Text="{DynamicResource my_birthday}" />
</StackLayout>
Related doc: https://learn.microsoft.com/en-us/xamarin/xamarin-forms/xaml/resource-dictionaries
Best Regards,
Jarvan Zhang
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.