【问题标题】:MVVMCross Android: value with binding not updatedMVVMCross Android:未更新绑定的值
【发布时间】:2015-07-12 18:18:08
【问题描述】:

我使用 Xamarin(Android)+Mvvmcross 创建了简单的应用程序。我的 ViewModel 中有属性 Data(type 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 中更新了当前属性。

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

【问题讨论】:

    标签: c# android binding xamarin mvvmcross


    【解决方案1】:

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

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

    【讨论】:

    • 我没有改变我的答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-13
    • 2015-04-03
    相关资源
    最近更新 更多