【问题标题】:Mvvmlight, Xamarin.iOS nested binding in ObservableCollection itemMvvmlight,Xamarin.iOS ObservableCollection 项中的嵌套绑定
【发布时间】: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


    【解决方案1】:

    我假设newsitem.Image 是一个字符串,因为它来自一个通常不包含特定平台类型的 ViewModel。因此,您尝试将字符串分配给UIImage。您需要加载此名称的图像。

    imageView.Image = UIImage.FromBundle(news.Image);
    

    您的图片必须:

    • 存储在您的 iOS 项目中的Resources
    • 具有构建操作BundleResource
    • 如果news.Image 是“xyz”,则名称为xyz.png(jpg、bmp、... 也可以)

    【讨论】:

    • 您会假设这一点是有道理的。在尝试简化代码时,我似乎有点太模糊了。在我的特定实现中,我使用框架Splat 和值转换器的组合来实现跨平台图像加载。
    • 我编辑了问题中的代码以更好地反映图像转换。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-05
    • 2015-03-24
    • 2014-12-02
    • 2017-05-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多