WPF: Simple TextBox Data Binding

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 text box.

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

But the line is not displayed. Also, if the Name2 string Name2 periodically updated using TimerCallback , is there anything you need to do to make sure the text field is updated when the data changes?

+45
data-binding wpf textbox
Nov 12 '09 at 21:30
source share
3 answers

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

 public string Name2 { get; set; } 

Note that with this minimal implementation, your TextBox will not respond to programmatic changes in Name2. Thus, for your timer update script, you need to implement INotifyPropertyChanged:

 partial class Window1 : Window, INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; // usual OnPropertyChanged implementation private string _name2; public string Name2 { get { return _name2; } set { if (value != _name2) { _name2 = value; OnPropertyChanged("Name2"); } } } } 

You should move this to a separate data object, and not to your Window class.

+67
Nov 12 '09 at 21:44
source share

In your window, the necessary notifications about data binding that the grid requires to use as a data source, namely the INotifyPropertyChanged interface, are not executed.

The string "Name2" should also be a property, not a public variable, because data binding is used for properties.

The implementation of the necessary interfaces for using the object as a data source can be found here .

+5
Nov 12 '09 at 21:44
source share

Just for future needs.

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

 <Grid Name="myGrid" Height="437.274"> <TextBox Text="{Binding Path=Name2, ElementName=window}"/> </Grid> 
+4
Jun 11 '15 at 16:41
source share



All Articles