Why does view.aBOX only update TextBoxA from within MainWindow? and how to I fix that?
When I pass view to w, it runs perfectly fine. Even the debugger shows view.aBOX being updated with the message in w. However, it never updates TextBoxA from within w.
Example code:
//MAIN
public partial class MainWindow : Window
{
ViewModel view; //DEBUGGER SHOWS aBOX = "Worker STARTED", But no update
Worker w;
public MainWindow()
{
this.view = new ViewModel();
this.DataContext = this.view;
//TEST
this.view.aBOX = "BINDING WORKS!!"; //UPDATES FINE HERE
this.w = new Worker(this.view);
}
}
//VIEW
public class ViewModel
{
public string aBOX { get; set; }
}
//WORKER
public class Worker
{
ViewModel view;
public Worker(ViewModel vm)
{
this.view = vm;
this.view.aBOX = "Worker STARTED"; //NEVER SEE THIS IN TextBoxA
}
}
//XAML/WPF
<TextBox Name="TextBoxA" Text="{Binding Path=aBOX, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" />
You need to implement INotifyPropertyChanged for changes to be propagated to the binding engine.
If you are able to use a base class, you could use this:
public class Notify : INotifyPropertyChanged
{
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(Expression<Func<object>> exp)
{
string propertyName = ((exp.Body as UnaryExpression).Operand as MemberExpression).Member.Name;
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
Using it:
public int Property
{
//getter
set
{
property = value;
RaisePropertyChanged(() => Property);
}
}
With this code, you can easily refactor the property and don't have to deal with magic strings. Also, you get intellisense.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With