WPF,为什么我的绑定只从主窗口更新

本文关键字:窗口 更新 绑定 为什么 我的 WPF | 更新日期: 2023-09-27 17:50:24

为什么view.aBOX只从MainWindow内部更新TextBoxA ?我该怎么解决这个问题?

当我将view传递给w时,它运行得非常好。甚至调试器也显示view.aBOX正在用w中的消息进行更新。但是,它从不从w中更新TextBoxA

示例代码:

//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}" />

WPF,为什么我的绑定只从主窗口更新

您需要实现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);
  }  
}
使用这段代码,您可以轻松地重构属性,而不必处理魔法字符串。此外,您还可以获得智能感知