Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 481
Warpin Avatar asked Nov 12 '09 21:11

Warpin


People also ask

How do I bind a TextBox in WPF?

One-Way Data Binding First of all, create a new WPF project with the name WPFDataBinding. The following XAML code creates two labels, two textboxes, and one button and initializes them with some properties.

What is databinding in WPF?

Data binding in Windows Presentation Foundation (WPF) provides a simple and consistent way for apps to present and interact with data. Elements can be bound to data from different kinds of data sources in the form of . NET objects and XML.

How do you control when the TextBox updates the source?

If you want the source to be updated as you type, set the UpdateSourceTrigger of the binding to PropertyChanged. In the following example, the highlighted lines of code show that the Text properties of both the TextBox and the TextBlock are bound to the same source property.


1 Answers

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.

like image 117
itowlson Avatar answered Sep 22 '22 09:09

itowlson