为什么view.aBOX
仅在TextBoxA
内更新MainWindow
?以及如何解决这个问题?
当我将view
传递给w
时,它运行得非常好。甚至调试器也会使用view.aBOX
中的消息更新w
。但是,它永远不会从TextBoxA
内更新w
。
示例代码:
//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}" />
答案 0 :(得分:4)
您需要实现INotifyPropertyChanged
才能将更改传播到绑定引擎。
如果您能够使用基类,则可以使用:
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
}
使用它:
public int Property
{
//getter
set
{
property = value;
RaisePropertyChanged(() => Property);
}
}
使用此代码,您可以轻松地重构属性,而不必处理魔术字符串。此外,你得到intellisense。