question

JassimAlRahma-9056 avatar image
0 Votes"
JassimAlRahma-9056 asked JassimAlRahma-9056 commented

Bind to a static variable inside App.xaml

Hi,

How can I bind my XAML to a static variable inside the App.xaml.cs?

For example:

 namespace Mawaqeet
 {
     public partial class App : Application
     {
         public static string my_name { get; set; }
         public static DateTime my_birthday { get; set; }
    
         public App()
         {


and then:

 <Label Text="{Binding App.my_name}" />
 <Label Text="{Binding my_birthday, StringFormat='{0:MMMM dd}'}" />


Thanks,
Jassim

dotnet-xamarin
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

JarvanZhang-MSFT avatar image
0 Votes"
JarvanZhang-MSFT answered JarvanZhang-MSFT edited

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://docs.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.


· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

But this will only work in the case of Text, what about other properties, let's say I want to save the FlowDirection as a static variable in App.xaml or App.xaml.cs and the use it in my page like this:


 FlowDirection={GET IT FROM STATIC VARIABLE}


0 Votes 0 ·