WPF,为什么我的绑定只从MainWindow更新?

WPF,为什么我的绑定只从MainWindow更新?

问题描述:

为什么view.aBOX只从MainWindow内更新TextBoxA?以及如何解决这个问题?WPF,为什么我的绑定只从MainWindow更新?

当我通过vieww,它运行得很好。即使调试器显示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}" /> 

您需要实现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。

+0

工作。谢谢!这不会发生我可以使用的汽车房地产改变协议?伪示例:'public string aBOX {get;设置{OnPropertyChanged(“aBOX”); }}。该修复超过了双倍我的视图代码.. – PiZzL3 2011-04-18 18:40:08

+1

@ PiZzL3 - 还没有,但你可以[投票](http://dotnet.uservoice.com/forums/40583-wpf-feature-suggestions/suggestions/478802-modify-该语言允许为可观察适当的?ref =标题)将它添加为未来的功能。 – CodeNaked 2011-04-18 18:45:47

+0

非常酷!谢谢! – PiZzL3 2011-04-18 18:47:40

您是否尝试过将VM作为参考发送?