Data binding a string variable of static class to textBlock in Phone 7?

14,141

You can't bind to a static class as binding requires an object instance.

You can, however, bind to static properties of a class.
You could use the following technique if you changed Global to not be static but left all it's properties as static.

Assuming:

namespace StaticBinding
{
    public class MyStaticClass
    {
        private static string myStaticProperty = "my static text";

        public static string MyStaticProperty
        {
            get { return myStaticProperty; }
            set { myStaticProperty = value; }
        }
    }
}

Then, if you define the following application resource:

.. xmlns:myns="clr-namespace:StaticBinding"

<Application.Resources>
    <myns:MyStaticClass x:Key="MyStaticClassResource" />
</Application.Resources>

Then in your page you can simply do the following:

<TextBlock Text="{Binding Path=MyStaticProperty, 
                  Source={StaticResource MyStaticClassResource}}" />

This will even give you intellisense on the Path.

This allows you to bind to "global" static variables and still leave the datacontext free to just contain any model you wish to bind to.

Share:
14,141
shoayb
Author by

shoayb

Updated on June 04, 2022

Comments

  • shoayb
    shoayb almost 2 years

    Here is the C# code

    public static class Global
    {
        public static string Temp 
        { 
            get 
            {
                return temp;
            }
            set
            {
                temp = value;
            }
        }
    
        public static string temp="100";
    
    }
    

    and here is the xaml code of MainPage

     <TextBlock Text="{Binding Path=Temp}" Grid.Column="1" Margin="34,47,32,49" Name="textBlockCheck" />
    

    I have declared the datacontext in MainPage.cs like this in its constructor:

    this.DataContext= Global.Temp;
    

    But there is nothing being displayed there in the textBlock. Thanks in advance for help.