2014-02-09 24 views
0

問題已在其他線程中得到解答,但我沒有得到完整答案。我做了一些四處走動和工作,但我對此並不滿意。 所以我問如何在MVVM模式中做到這一點。如何從後臺線程上升PropertyChanged

我在View中的文本框中更新值時遇到了令人沮喪的問題。 Proprerty消息正在從我的回調中更新,但不顯示在GUI中。屬性正確綁定。現在我可以做到這一點。原因是我沒有提高UI線程上的PropertyChanged,因爲我從回調調用它。我正在嘗試,但沒有任何工作。如何在UI線程上引發PropertyChange事件?

編輯再次刷新CODE:

namespace test 
{ 
    public class MainViewModel : INotifyPropertyChanged, IDataExchangeCallback 
    { 
     public MainViewModel() 
     { 
      Message = "TEST1"; 
     } 

     void IDataExchangeCallback.Result(string result) 
     { 
      Message += result; 
     } 

     public void Register() 
     { 
      InstanceContext instanceContext = new InstanceContext(new MainViewModel()); 
      DataExchangeClient client = new DataExchangeClient(instanceContext); 

      client.RegisterClient(Guid.NewGuid().ToString()); 
     } 

     private string _message; 
     public string Message 
     { 
      get { return this._message; } 
      set 
      { 
       if (this._message != value) 
       { 
        this._message = value; 
        OnPropertyChanged("Message"); 
       } 
      } 
     } 

     public event PropertyChangedEventHandler PropertyChanged; //ALWAYS NULL!!! BUT I HAVE INotifyPropertyChanged implement 
     protected void OnPropertyChanged(string name) 
     { 
      PropertyChangedEventHandler handler = PropertyChanged; 
      if (handler != null) 
      { 
       Application.Current.Dispatcher.Invoke(() => 
        handler(this, new PropertyChangedEventArgs(name))); 
      } 
     } 
    } 
} 

我PropertChange總是空。爲什麼?當我使用綁定時,它應該訂閱PropertyChanged。

編輯 我仍然需要幫助

+0

我不是附近的VS,但現在確實有部分標示出的解決方案:(() Application.Current.Dispatcher.Invoke((動作)=> {處理程序(這一點,新PropertyChangedEventArgs(propertyName的))}); –

+0

這是**不**工作,我不知道爲什麼 – UserBuzzer

+0

不太確定,但它可能是你傳遞一個新的MainViewModel實例到:InstanceContext?你嘗試過傳遞:InstanceContext instanceContext = new InstanceContext(this); – rauland

回答

0

找到解決方案!

顯然,如果您要使用INotifyPropertyChanged,則需要在代碼中將其稱爲明確

this.DataContext = mvm;在XAML

public partial class MainWindow : Window 
{ 
    public MainWindow() 
    { 
     InitializeComponent(); 
     MainViewModel mvm = new MainViewModel(); 
     mvm.Register(); 

     this.DataContext = mvm; //this you need 
    } 
} 

宣言是不夠的:

<Window.DataContext> 
    <local:MainViewModel/> 
</Window.DataContext> 

如果有人能解釋我爲什麼我將不勝感激?