tags:

views:

2704

answers:

4

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"

+1  A: 

No it has to be a visible property.

Preet Sangha
+2  A: 

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.

Will
Or have the class implement INotifyPropertyChanged to have the binding work automatically.
Lars Truijens
There's nothing automatic about INPC. You have to do all the heavy lifting. But that would be silly in this instance as he's binding to the Window, which is, in fact, a DependencyObject and supports DP's out of the box. So advising him to implement INPC would be like an unsharpened pencil.
Will
+3  A: 

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)

Examples:

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 PropertyChangedEventHandler PropertyChanged;
}

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 ...
}
Danny Varod
A: 

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

{Binding Text}
Neil