XAML data binding to a global variable?

13,529

Solution 1

First off you can only bind to properties, so you need to add a getter and setter.

public static bool is_verifying { get; set; }

Next you can either set the DataContext of your form to be your class here, and bind with a simple:

"{Binding is_verifying}"

Or create a reference to your class in the resources of the form and reference it like so:

<Window.Resources>
    <local:Login x:Key="LoginForm"/>
</Window.Resources>
...

<TextBox Text="{Binding Source={StaticResource LoginForm}, Path=is_verifying}"/>

Solution 2

You can't bind to a field, you'll need to make it a Property, and still, then you won't be notified of changes unless you implement some kind of notification mechanism, which can be achieved e.g. by implementing INotifyPropertyChanged or by making the property a DependencyProperty.

When you have a property, you can usually use the x:Static markup extension to bind to it.

But binding to a static property requires some tricks, which might not work in your case since they require either creating a dummy instance of your class or making it a singleton. Also i think at least in Windows phone 7 x:Static is not available. So you might want to consider making the property an instance property, maybe on a separate ViewModel which you can then set as a DataContext.

Share:
13,529
Travv92
Author by

Travv92

Updated on July 23, 2022

Comments

  • Travv92
    Travv92 almost 2 years

    How can I bind a TextBoxes Text to a global variable in my class in XAML? This is for Windows Phone by the way.

    Here is the code:

        namespace Class
        {
        public partial class Login : PhoneApplicationPage
        {
            public static bool is_verifying = false;
    
            public Login()
            {
                InitializeComponent();        
            }
    
    
            private void login_button_Click(object sender, RoutedEventArgs e)
            {
                //navigate to main page
                NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.RelativeOrAbsolute));
            }
    
            private void show_help(object sender, EventArgs e)
            {
                is_verifying = true;
            }
          }
    
        }
    

    And I want to bind a Textboxes text to "is_verifying".

    Thanks.

  • Travv92
    Travv92 over 11 years
    Thanks for that! I already had some success with KDiTraglia's solution but your answer provides some useful insight! Also, in XAML for VS2012 and Windows Phone applications, there doesn't seem to be an "x:static", only "x:Null" and "x:StaticResource".
  • Botz3000
    Botz3000 over 11 years
    @Travv92 I just found out that at least WP7 doesn't support x:Static. I added an alternative (and IMO better) solution at the end of my answer. The point about INotifyPropertyChanged/DependencyProperty still applies to that though.