WPF Binding to local variable

93,833

Solution 1

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( ... );
}

Solution 2

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}"

Solution 3

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>
Share:
93,833
PrimeTSS
Author by

PrimeTSS

Updated on February 18, 2022

Comments

  • PrimeTSS
    PrimeTSS about 2 years

    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"