【问题标题】:How to Binding Image From ViewModel Without Listview On Xamarin如何在 Xamarin 上不使用 Listview 从 ViewModel 绑定图像
【发布时间】:2018-01-23 08:09:29
【问题描述】:

我创建了具有 3 个数据的模型,即 id、name、image

public class PromoB
{
    public string id { get; set; }
    public string name { get; set; }
    public string image { get; set; }
}

并且此数据是从 HttpGetMethod 获得的,我能够获取数据并将其绑定到我的列表视图。但是当我只想选择图像并将其绑定到我的图像源时,我仍然感到困惑。我尝试将我的 ImageSource 绑定到 PromoB(我的模型),但图像没有显示出来。这是我现在的视图模型

private ObservableCollection<PromoB> promo;
public ObservableCollection<PromoB> Promo
{
    get { return promo; }
    set { promo = value; }
}

public PromoViewModel()
{
    // Here you can have your data form db or something else,
    // some data that you already have to put in the list

    Promo = new ObservableCollection<PromoB>();

    // Web service call to update list with new values  

    MyHTTP.GetPromoB(list =>
    {
        foreach (PromoB item in list)
            Promo.Add(item);
    });
}

我的任务是获取数据

public static async Task GetPromoB(Action<IEnumerable<PromoB>> action)
{
    string sUrl = "myurl";
    string sContentType = "application/json"; // or application/xml

    HttpClient oHttpClient = new HttpClient();
    var oTaskPostAsync = await oHttpClient.GetAsync(sUrl);
    if (oTaskPostAsync.IsSuccessStatusCode)
    {
        string content = await oTaskPostAsync.Content.ReadAsStringAsync();
        List<PromoB> o = JsonConvert.DeserializeObject<List<PromoB>>(content);
        action(o);
    }
}

我尝试像这样在我的视图中绑定数据

<Image Source="{Binding Promo}" HeightRequest="167" />

所以我应该如何准确地将数据绑定到我的 ImageSource,因为在列表视图中我首先将 mylistview 绑定到 PromoB,然后我使用图像绑定标签使用名称绑定 ImageSource。我仍然不熟悉 viewmodel 。您的回答对我很有帮助,谢谢

这是我的完整 Xaml

<StackLayout Spacing="0">
    <Image Source="{Binding Promo}" 
           HeightRequest="167" />   
</StackLayout>

【问题讨论】:

  • 什么是 PromoDB.image?是网址吗?
  • 是的,我的 PromoDb.image 是一个 url
  • @EvZ 那么我究竟是如何获得图像的?使用这个公共 Uri ProductImage { get;放; } ?然后什么 ?但我的任务是反序列化为 PromoB 模型
  • 假设您已将列表视图的 ItemSourcee 设置为“Promo”:

标签: c# mvvm xamarin.forms


【解决方案1】:
  1. 鉴于 Items 属于 ObservableCollection&lt;PromoB&gt; 使用 FlowItemsSource = {Binding Items}.. 您也使用默认的 ItemsSource

  2. 确保BindingContext 的类型为PromoViewModel

  3. 您正在使用Promo,但您可能的意思是Promo.image,而且Promo 需要属于BindingContext

【讨论】:

  • 问题不在我的 flowlistview 中。但是在flowlistview上方的图像,我想将最新图像显示为标题,但我不知道如何绑定它,以及为什么我还要编写itemsource,因为起初我不知道应该使用哪个,但它工作正常。
  • ImageItems 的上下文是否相同?不要同时使用,只使用FlowItemsSource
  • 您向我们展示的 ViewModel 和 Xaml 丝毫不匹配。发布你的代码,它正在工作。
  • 没有我使用 Promo 作为上下文,我将编辑我的问题
  • PromoItems 必须属于同一个BindingContext
猜你喜欢
  • 2021-10-20
  • 1970-01-01
  • 2018-02-12
  • 1970-01-01
  • 2018-10-19
  • 1970-01-01
  • 2023-03-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多