59

I have this class:

public partial class Window1 : Window
{
    public String Name2;

    public Window1()
    {
        InitializeComponent();
        Name2 = new String('a', 5);
        myGrid.DataContext = this;
    }

    // ...
}

And I want to display the string Name2 in the textbox.

<Grid Name="myGrid" Height="437.274">
  <TextBox Text="{Binding Path=Name2}"/>
</Grid>

But the string isn't displayed. Also, if the string Name2 is updated periodically using a TimerCallback, do I need to do anything to make sure the textbox is updated when the data changes?

lelimacon
  • 87
  • 1
  • 9
Warpin
  • 6,971
  • 12
  • 51
  • 77
  • 3
    As a tip, you can format code by indenting by four spaces or using the 101010 button -- saves manually mucking around with br tags and escaping angle brackets! – itowlson Nov 12 '09 at 21:39

3 Answers3

91

Name2 is a field. WPF binds only to properties. Change it to:

public string Name2 { get; set; }

Be warned that with this minimal implementation, your TextBox won't respond to programmatic changes to Name2. So for your timer update scenario, you'll need to implement INotifyPropertyChanged:

partial class Window1 : Window, INotifyPropertyChanged
{
  public event PropertyChangedEventHandler PropertyChanged;

  protected void OnPropertyChanged(string propertyName)
  {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
  }

  private string _name2;

  public string Name2
  {
    get { return _name2; }
    set
    {
      if (value != _name2)
      {
         _name2 = value;
         OnPropertyChanged("Name2");
      }
    }
  }
}

You should consider moving this to a separate data object rather than on your Window class.

RickNZ
  • 18,448
  • 3
  • 51
  • 66
itowlson
  • 73,686
  • 17
  • 161
  • 157
  • Example from MSDN on implementing the INotifyPropertyChanged interface (scroll down to DemoCustomer implementation): http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged(v=vs.110).aspx – Juha Palomäki Nov 27 '13 at 20:16
  • Following your example I do But it does not work – Ph0b0x Aug 05 '19 at 15:43
10

Just for future needs.

In Visual Studio 2013 with .NET Framework 4.5, for a window property, try adding ElementName=window to make it work.

<Grid Name="myGrid" Height="437.274">
  <TextBox Text="{Binding Path=Name2, ElementName=window}"/>
</Grid>
Stefan Cantacuz
  • 131
  • 1
  • 3
9

Your Window is not implementing the necessary data binding notifications that the grid requires to use it as a data source, namely the INotifyPropertyChanged interface.

Your "Name2" string needs also to be a property and not a public variable, as data binding is for use with properties.

Implementing the necessary interfaces for using an object as a data source can be found here.

Darien Ford
  • 1,049
  • 7
  • 17