× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Binding label to a variable

Gayot Fow
Feb 05, 2015
<p>Your code will work if you change your class to this...</p> <pre><code> public partial class Window1 : Window, INotifyPropertyChanged { private int _idCounter; public int IdCounter { get { return _idCounter; } set { if (value != _idCounter) { _idCounter = value; OnPropertyChanged("IdCounter"); } } } public Window1() { InitializeComponent(); myLabel.SetBinding(ContentProperty, new Binding("IdCounter")); DataContext = this; } private void Button_Click(object sender, RoutedEventArgs e) { e.Handled = true; IdCounter++; } #region INotifyPropertyChanged Implementation public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged(string name) { var handler = System.Threading.Interlocked.CompareExchange(ref PropertyChanged, null, null); if (handler != null) { handler(this, new PropertyChangedEventArgs(name)); } } #endregion } </code></pre> <p>Some of the issues you were having are...</p> <p>The window itself should implement INotifyPropertyChanged so that the binding engine can place an ear on it.</p> <p>the IdCounter needs to be public and have a public getter on it so that the binding engine can 'get' it.</p> <p>You should set the DataContext to whatever class has declared IdCounter (the MainWindow in this case). Part of the problem was that the binding engine had no DataContext.</p> <p>The BindingMode setting was a red-herring since a Label binds that way by default.</p> <p>The UpdateSourceTrigger was a red-herring since the content of the label does not have a mechanism to update the source property. A label's content is not like a text box where the user can type something that the code needs to know about. When you're binding to something that the user cannot change, forget about UpdateSourceTrigger, it's the <strong>Target</strong> property that counts.</p> <p>The handler should mark the event. This is good practice and did not affect the binding.</p> <p>The binding constructor needs only the path.</p> <p>This code will give you your expected result; i.e., that the label updates when the button is clicked. Checked, compiled, and executed on vs2013, .net 4.5.</p> <p>The other respondents said you should use a View Model. I agree with this 100%, and overall it's a good thing to consider.</p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/23716059/Binding%20label%20to%20a%20variable/23716387">Stack Overflow</a>.</p>
comments powered by Disqus