c# - Xamarin Android 数据绑定(bind)与 MVVM Light

标签 c# android android-fragments xamarin mvvm-light

原始问题:

我在尝试使用 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/

相关文章:

c# - EF 一对一关系改变实体与另一个实体(替代)

c# - TaskScheduler - 执行延续

C# 包含行为

android - 使用 JNI 传递和返回 OpenCv Mat 对象

java - This release is not compliant with the Google Play 64-bit requirement error still after adding libraries

java - 更改 fragment 中的颜色

c# - 我怎么知道我的程序在单元测试环境下

android - "ArrayAdapter requires the resource ID to be a TextView"XML 问题

java - 为什么我会遇到类强制转换异常?安卓

java - 如何将值从 NavigationDrawerFragment.java 传递到 MainActivity.java 然后传递到 AnotherFragment 页面