WPF Binding to local variable

Can you bind to a local variable like this?

SystemDataBase.cs

namespace WebWalker
{
    public partial class SystemDataBase : Window
    {
        private string text = "testing";
...

SystemDataBase.xaml

 <TextBox 
       Name="stbSQLConnectionString" 
       Text="{SystemDataBase.text}">
 </TextBox>

??

Text is set to the local variable "text"


The pattern is:

public string Text {get;set;}

and the binding is

{Binding Text, RelativeSource={RelativeSource FindAncestor, AncestorType=Window}}

If you want the binding to update automatically you should make it a DependencyProperty.


I think 3.5 added ElementName to bindings, so the following is a little easier:

<Window x:Name="Derp" ...
  <TextBlock Text="{Binding Text, ElementName=Derp}"/>

To bind to a local "variable" the variable should be:

  1. A property, not a field.
  2. Public.
  3. Either a notifying property (suitable for model classes) or a dependency property (sutable for view classes)

Notifying property example:

public MyClass : INotifyPropertyChanged
{
    private void PropertyType myField;

    public PropertyType MyProperty
    {
        get
        {
            return this.myField;
        }
        set
        {
            if (value != this.myField)
            {
                this.myField = value;
                NotifyPropertyChanged("MyProperty");
            }
        }
    }

    protected void NotifyPropertyChanged(String propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

Dependency property example:

public MyClass : DependencyObject
{
    public PropertyType MyProperty
    {
        get
        {
            return (PropertyType)GetValue("MyProperty");
        }
        set
        {
            SetValue("MyProperty", value);
        }
    }

    // Look up DependencyProperty in MSDN for details
    public static DependencyProperty MyPropertyProperty = DependencyProperty.Register( ... );
}

If you're doing a lot of this, you could consider binding the DataContext of the whole window to your class. This will be inherited by default, but can still be overridden as usual

<Window DataContext="{Binding RelativeSource={RelativeSource Self}}">

Then for an individual components you can use

Text="{Binding Text}"

To bind a local variable which is present in your Window class it has to be : 1. Public property 2. A notifying property. For this your window class should implement INotifyPropertyChanged interface for this property.

Then in the constructor

public Assgn5()
{           
    InitializeComponent();

    this.DataContext = this; // or **stbSQLConnectionString**.DataContext = this;
}

 <TextBox 
   Name="stbSQLConnectionString" 
   Text="{Binding text}">
 </TextBox>