2015-05-03 54 views
1

我使用Xamarin(Android)+ Mvvmcross創建了簡單的應用程序。我有我的ViewModel屬性數據(鍵入MyData)。MVVMCross Android:綁定值未更新

這是我VievModel

public class MyViewModel:MvxViewModel 
{ 
    private MyData _data; 
    public MyData Data 
    { 
     get { return _data; } 
     set 
     { 
      _data = value; 
      RaisePropertyChanged(() => Data); 
     } 
    } 
    .... 
} 

public class MyData: INotifyPropertyChanged 
{ 
    public string Current 
    { 
     get { return _current; } 
     set 
     { 
      _current = value; 
      Debug.WriteLine(_current); 
      NotifyPropertyChanged("Current"); 
     } 
    } 
    private string _current; 

    public event PropertyChangedEventHandler PropertyChanged; 
    public void NotifyPropertyChanged(string propertyName) 
    { 
     if (PropertyChanged != null) 
     { 
      PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
     } 
    } 
} 

我用鑑於

xmlns:local="http://schemas.android.com/apk/res-auto" 

<TextView 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
local:MvxBind="Text Data.Current" 
android:id="@+id/textView" /> 

這種結合這是我的計時器:

private Timer _timer; 
..... 
public void InitEvent(Action action) 
{ 
    _timer.Elapsed += TimerTick; 
    _action = action; 
} 

private void TimerTick(object sender, ElapsedEventArgs e) 
{ 
    if (_action != null) 
      _action(); 
} 

在_action更新proprrty電流。

更新value屬性時TextView中的文本不會更改。問題是什麼? 該值在計時器上發生變化。 Debug.WriteLine(_current) - 顯示新的值。 TextView.Text - 舊值,未更新。

回答

5

你的「計時器」是否在後臺線程上運行?

如果是,那麼你需要找到某種方式在UI線程上發信號給RaisePropertyChanged

一個簡單的方法是從MvxNotifyPropertyChanged繼承 - 它會自動將通知編組到UI。

另一個是使用IMvxMainThreadDispatcher - 例如,

public string Current 
{ 
    get { return _current; } 
    set 
    { 
     _current = value; 
     Debug.WriteLine(_current); 
     Mvx.Resolve<IMvxMainThreadDispatcher>() 
      .RequestMainThreadAction(() => NotifyPropertyChanged("Current")); 
    } 
} 

當然,如果將多個線程訪問set Current那麼你也可能會碰到奇怪的線程錯誤......

+0

我沒有改變我的回答 – Stuart

+0

它的作品。謝謝。 – FetFrumos