我用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上更新了proprty电流。
当Value属性是在TextView中更新文本时,不会更改。问题是什么? 该值在计时器上更改。debug.writeline(_current) - 显示新值。textview.text-旧值,未更新。
是您的"计时器"在背景线程上运行吗?
如果是,那么您需要找到某种方法来发出UI线程上的RaisePropertyChanged
。
做到这一点的一种简单方法是从MvxNotifyPropertyChanged
继承 - 它将自动将通知元使用。
另一个是使用IMvxMainThreadDispatcher
-例如
public string Current
{
get { return _current; }
set
{
_current = value;
Debug.WriteLine(_current);
Mvx.Resolve<IMvxMainThreadDispatcher>()
.RequestMainThreadAction(() => NotifyPropertyChanged("Current"));
}
}
当然,如果多个线程正在访问set Current
,那么您也可能会击中怪异的线程错误...