MVVMCross Android:绑定未更新的值

Fet*_*mos 1 c# binding android mvvmcross xamarin

我用Xamarin(Android)+ Mvvmcross创建了简单的应用程序.我的ViewModel中有属性Data(类型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));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我在视图中使用此绑定

 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" />
Run Code Online (Sandbox Code Playgroud)

这是我的计时器:

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

 private void TimerTick(object sender, ElapsedEventArgs e)
 {
     if (_action != null)
            _action(); 
 }
Run Code Online (Sandbox Code Playgroud)

在_action更新的proprrty当前.

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

Stu*_*art 5

您的"计时器"是否在后台线程上运行?

如果是,那么你需要找到一些方法RaisePropertyChanged在UI线程上发出信号.

一种简单的方法是继承MvxNotifyPropertyChanged- 它会自动将通知封送到UI.

另一种是使用IMvxMainThreadDispatcher- 例如

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

当然,如果多个线程正在访问,set Current那么你也可能遇到奇怪的线程错误......