2016-04-17 72 views
0

比方說,我有這個類的RaiseProperyChanged屬性從PostSharp:RaisePropertyChanged上Porperty在另一個線程更新不叫

[NotifyPropertyChanged] 
public class MainViewModel 
{ 
    public int RandInt { get; set; } 

    public MainViewModel() 
    { 
     RandInt = 10; 
     new Task(TaskStart).Start(); 
    } 

    private void TaskStart() 
    { 
     Random rand = new Random(); 
     while (true) 
     { 
      RandInt = rand.Next(9999); 
     } 
    } 
} 

綁定RandInt標籤或其他控制WIL結果中沒有標籤的變化。這意味着標籤的值始終爲10,因爲該屬性是從另一個線程更改的。如何處理這種奇怪的行爲?使用MVVM Light在屬性設置器中使用RaisePropertyChanged()可以正常工作。

+0

這可能是http://stackoverflow.com/questions/17065810/asynchronous-ui-update-from-viewmodel-in-wpf – joncloud

+0

的副本,請讓我們知道,如果(可能)重複給你答案。 –

+0

當然不是因爲這個問題與我無關。我是明確的PostSharp ... 但是我已經做了一個錯誤報告,我在等待結果 – chris579

回答

1

這是PostSharp的設計結果。問題是方法TaskStart由方面[NotifyPropertyChanged]檢測,最後刷新事件隊列,但此方法不會結束。

這將在未來版本的PostSharp中解決。同時,您可以使用方法NotifyPropertyChangedServices.RaiseEventsImmediate()。見例如:

[NotifyPropertyChanged] 
public class MainViewModel 
{ 
    public int RandInt { get; set; } 

    public MainViewModel() 
    { 
     RandInt = 10; 
     new Task(TaskStart).Start(); 
    } 

    private void TaskStart() 
    { 
     Random rand = new Random(); 
     while (true) 
     { 
      AsyncRandomNumber = random.Next(9999); 

      // Raise the events now, because the method TaskStart never ends. 
      NotifyPropertyChangedServices.RaiseEventsImmediate(this); 
     } 
    } 
} 
+0

我會小心的,如果你不等待'InvokeAsync',你會淹沒消息隊列可能更好的做法是執行'dispatcher.Invoke('而不是。另外,你也可能想要傳入一個DispatcherPriority.Input,因此它與輸入(5)相同,而不是缺省值(9)數字先走 –

+0

WPF對於在不同線程中完成的更改沒有反應,這基本上是不正確的。使用RaisePropertyChanged(使用MVVM Light甚至是自寫的)的通用(非AOP)實現可以工作。起訴涉及PostSharp而不是WPF。正如過去已經報道的那樣,我認爲它仍然沒有修復, – chris579

+0

@ chris579:你說得對。我們已經調查了更多,並找到了此代碼無法工作的真正原因。對不起,我已經更新了我的答案。 –

相關問題