MVVMCross Android:绑定的值未更新

MVVMCross Android: value with binding not updated

我使用 Xamarin(Android)+Mvvmcross 创建了简单的应用程序。我的 ViewModel 中有 属性 数据(类型 MyData)。

这是我的 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 中更新了当前属性。

更新值 属性 时,TextView 中的文本不会更改。问题是什么? 该值在计时器上更改。 Debug.WriteLine(_current) - 显示新值。 TextView.Text - 旧值,未更新。

您的 "timer" 运行 是否在后台线程中?

如果是,那么您需要找到一些方法在 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 那么您也可能遇到奇怪的线程错误...