原始问题:
我在尝试使用 MVVM Light 将我的 ViewModel 中的值绑定(bind)到 Xamarin Android 中的 TextView 时遇到问题。该值更改一次,然后停止工作。即使 ViewModel 中的对象发生变化并且绑定(bind)模式设置为默认值 (OneWay)。
由于业务需要,我需要继续使用 MVVM Light 和 Xamarin Android。
例子:
在我的第一个 fragment 中,我有一个书籍列表,它绑定(bind)到我的 ViewModel 中的一个书籍列表。在我的 Viewmodel 中,我有一个名为 CurrentBook 的对象,它随着我列表中的一个 onclick 事件而改变。
VM.CurrentBook = Books[index];
在我的第二个 fragment 中,我将标题绑定(bind)到 TextView
_titleBinding = this.SetBinding(() => VM.CurrentBook.Title, () => TitleTextView.Text);
Current book 第一次从 NULL 变为 Book 的实例时,标题会根据需要更改。第一次更改 VM.CurrentBook = Books[index]; 后,标题与第一本书相同。
更新:
在 Milen Pavlov 的帮助下,我尝试了一些事情, 我试着改成
VM.SetBinding(() => VM.CurrentBook.Title, TitleTextView, () => TitleTextView.Text, BindingMode.TwoWay);
这触发了一个错误:
System.Reflection.TargetException: Object of type '[Solution].Client.Shared.ViewModels.BooksViewModel' doesn't match target type '[Solution].Client.Android.BookDetailsFragment'
我试过的另一件事:
_titleBinding = this.SetBinding(() => VM.CurrentBook.Title, TitleTextView, () => TitleTextView.Text, BindingMode.TwoWay);
enter code here
这触发了另一个错误:
System.Reflection.TargetException: Object of type 'Android.Support.V7.Widget.AppCompatTextView' doesn't match target type '[solution].Client.Android.BookDetailsFragment'
最佳答案
在 xamarin android 和 mvvm-light 上进行数据绑定(bind)时,我一直在使用这个重载:
VM.SetBinding(() => VM.CurrentBook.Title, TitleTextView, () => TitleTextView.Text, BindingMode.TwoWay);
希望对您有所帮助。
关于c# - Xamarin Android 数据绑定(bind)与 MVVM Light,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35197870/