【发布时间】:2016-03-29 11:02:01
【问题描述】:
我正在构建一个使用 Xamarin.iOS 和 mvvmlight 作为 mvvm 框架的跨平台解决方案。
我遇到了嵌套绑定的问题。我正在尝试在 Xamarin.iOS 中完成以下 windows phone 示例:
我有一个 NewsItem 类型的可观察集合,称为 NewsList,我绑定到 Listview
<ListView ItemsSource="{Binding NewsList}" >
此列表最初填充了具有空图像的新闻项目。在加载图像时,每个项目的图像属性都会更新。
NewsItem 模型的图像属性在设置时引发属性更改事件。
并且图片源绑定是在xaml中的ListView.ItemTemplate中创建的:
<ListView.ItemTemplate>
<DataTemplate>
...
<Image Source="{Binding Image}" />
此绑定适用于 Windows Phone。图像最初在填充集合时更新,图像在加载时更新。
但是,当尝试在 Xamarin.iOS 中设置此绑定时,我遇到了问题。
按照给出的 iOS 绑定示例,我在 ObservableCollection 上使用了 GetController 函数:
newsTableViewController = NewsListHolder.GetController(CreateNewsCell, BindNewsCell);
在BindNewsCell 中,我尝试设置图像绑定,就像上面的windows phone 示例一样。然而事实证明这很困难:
private void BindNewsCell(UITableViewCell cell, NewsItem news, NSIndexPath path)
{
// Reference for UI elements in cell
var titleLabel = cell.ViewWithTag (100) as UILabel;
var dateLabel = cell.ViewWithTag (101) as UILabel;
var imageView = cell.ViewWithTag (102) as UIImageView;
// Set values in cell
titleLabel.Text = news.Title;
dateLabel.Text = news.Date;
// The line commented out below works in setting the image, but does not update
// when the image property changes, only when the cells are redrawn.
//imageView.Image = ValueConverter.IBitmapToUIImage(news.Image);
this.SetBinding (
() => news.Image,
() => imageView.Image)
.ConvertSourceToTarget(ValueConverter.IBitmapToUIImage);
}
此绑定不起作用。我也尝试过使用:
this.SetBinding(
() => news.Image)
.WhenSourceChanges(
() =>
{
imageView.Image = ValueConverter.IBitmapToUIImage(news.Image);
});
没有成功。
我可以做常规绑定:
private Binding<bool, bool> testBinding;
// Set test binding
testBinding = this.SetBinding (
() => Vm.Test,
() => TestIndicator.Hidden));
工作正常。
如何绑定到可观察集合中动态创建的项目的属性?
编辑:我已经修改了上述过度简化的代码示例,以包含更多关于图像转换的细节。
归结为问题:在 xamarin.ios 中使用 mvvmlight,我如何在所述项目的可观察列表中对项目的特定属性实现数据绑定?
【问题讨论】:
标签: data-binding xamarin xamarin.ios mvvm-light