c# - Xaml - 如何使用 ViewModel 中的 ImageSource

标签 c# xaml xamarin xamarin.forms imagesource

我有一个 ObservableCollection<Item>和一个 Item包含文件路径和 ImageSource来自磁盘的一些图像。

public ObservableCollection<Item> Items { get; set; } = new ObservableCollection<MediaListItem>();
public class Item
{
    public string Image { get; set; } // Full path to the image
    public ImageSource ImageSource { get; set; }
}

但是,我无法访问这两个属性中的任何一个,也无法通过 XAML 显示图像。

<ListView ItemsSource="{Binding MediaList}">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <StackLayout Padding="10">
                    <Image Source="{Binding ImageSource}" VerticalOptions="Fill"></Image>
                </StackLayout>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

现在我很困惑,因为我能够输出 string Image通过标签通过 XAML,但根本无法显示路径中的图像。

最佳答案

您可以像这样使用 ImageSource.FromFile()ImageSource.FromUri()

在 Xaml 中

<Image  Source="{Binding  ImageSource}"  Aspect="AspectFit"  ></Image>

在代码中

public ObservableCollection<Item> MediaList { get; set; } = new ObservableCollection<Item>()
        {
            new Item
            {
                ImageSource = ImageSource.FromFile("xamarin.png")
            },
            new Item
            {
                ImageSource = ImageSource.FromUri(new Uri("/image/4mMod.png"))
            }
        };

结果

enter image description here

更新

取决于Microsoft-Local Images

Image files can be added to each application project and referenced from Xamarin.Forms shared code...

To use a single image across all apps, the same filename must be used on every platform, and it should be a valid Android resource name (ie. only lowercase letters, numerals, the underscore, and the period are allowed).

有关更多信息,请查看答案 here

现在如果你想显示一个图像而不把它添加到每个平台,你应该使用Converter .

例如:

  1. 在共享代码中创建一个名为 ImagesFolder 的新文件夹,然后将图像添加到其中

    enter image description here

  2. 在代码中,像这样创建一个名为 ByteArrayToImageSourceConverter 的新类

    public class ByteArrayToImageSourceConverter : IValueConverter 
    {
      public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
      {   
        byte[] bytes;
        var assembly = GetType().GetTypeInfo().Assembly; // using System.Reflection;
    
        var stream = assembly.GetManifestResourceStream((string)value); // value = "App1.ImagesFolder.ninja.png"
        using (var ms = new MemoryStream()) // using System.IO; 
        {
            stream.CopyToAsync(ms);
            bytes = ms.ToArray();
        }
        return ImageSource.FromStream(() => new MemoryStream(bytes));
      }
      public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
      {
        return null;
      }
    }
    

    查看模型

    public ObservableCollection<Item> MediaList { get; set; } = new ObservableCollection<Item>()
    {
        new Item
        {
           Image  = "App1.ImagesFolder.ninja.png"
        }
    };
    
  3. 在 Xaml 中

    <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:local="clr-namespace:App1"
         x:Class="App1.MainPage">
    
      <ContentPage.Resources>
        <ResourceDictionary>
           <local:ByteArrayToImageSourceConverter  x:Key="ByteArrayToImageSourceConverter" />
       </ResourceDictionary>
     </ContentPage.Resources>
    
     <ListView ItemsSource="{Binding MediaList}" >
        <ListView.ItemTemplate>
          <DataTemplate>
            <ViewCell>
               <Image Source="{Binding Image, Converter={StaticResource ByteArrayToImageSourceConverter}}" />
            </ViewCell>
          </DataTemplate>
       </ListView.ItemTemplate>
     </ListView>
    
    </ContentPage>
    

相关链接

ByteArrayToImageSourceConverter

Shared Resources

How to load binary images in Xamarin?

关于c# - Xaml - 如何使用 ViewModel 中的 ImageSource,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56313197/

相关文章:

javascript - 在客户端 Javascript 方法之后运行服务器方法

c# - 标记在 XML 命名空间中不存在

android - 如何更改 xamarin 表单中的导航页面后退按钮

c# - 使用JSON.net解析json字符串

xaml - 如何将 Xamarin.Forms XAML UI 页面转换为 PDF 文件?

c# - 在按钮 ASP.NET c# 上禁用回发

c# - 任务中的计时器未触发

c# - 更新mysql表出现错误

xaml - Expression Blend 有修剪/裁剪的概念吗?

c# - 在我的 WPF 应用程序中过度使用代码隐藏?