如何在Xamarin Forms(Android)上显示共享文件夹中的图像?

时间:2020-07-27 08:15:30

标签: c# image xaml xamarin.forms

我在以xamarin形式显示图像时遇到问题。该图像存储在我们网络上的共享文件夹中。我正在使用Sharpcifs。

以下是相关视图模型的代码:

this.getDataPath = function(data) {
  // If there are more than two levels, we'll just slice those off.        
  if( data.entry.length > 2 ) {
    return data.entry.slice(0,2);
  }
  return data.entry;
};

我用通用名称替换了域,用户名和密码。我确实使用了正确的域名,用户名和密码。 并在xaml中:

ImageSource ProductImage { get; set; }


    public ProductPositionsViewModel()
    {
        Title = "Produit/Pos";
        Items = new ObservableCollection<ListItem>();

        SharpCifs.Config.SetProperty("jcifs.smb.client.lport", "8080");

        //Get Auth
        var auth = new NtlmPasswordAuthentication("Domain","User","Password");

        //Get target's SmbFile.
        var smb = new SmbFile("smb://file/products/ABY/ABYBAG167.jpg", auth);

        Console.WriteLine($"exists? {smb.Exists()}");
        // It returns true, I can confirm.

        //Get readable stream.
        var readStream = smb.GetInputStream();

        
        

        //Create reading buffer.
        var memStream = new MemoryStream();

        //Get bytes.
        ((Stream)readStream).CopyTo(memStream);

        using (MemoryStream memorystream = memStream)
        {

            ProductImage = ImageSource.FromStream(() => memorystream);
        }

        

        //Dispose readable stream.
        readStream.Dispose();

        LoadItemsCommand = new Command(async () => await ExecuteLoadItemsCommand());
    }

1 个答案:

答案 0 :(得分:0)

如果您想在运行时设置Image的 Source ,请不要忘记在ViewModel中实现接口 INotifyPropertyChanged

public class ProductPositionsViewModel: INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;


  
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    ImageSource productImage;

    ImageSource ProductImage { 
        
        get
        {
            return productImage;
        }

        set
        {
            if(productImage!=value)
            {
                productImage = value;
                OnPropertyChanged("ProductImage");
            }
        }
    }


    public ProductPositionsViewModel()
    {

        //...
      
        using (MemoryStream memorystream = memStream)
        {

            ProductImage = ImageSource.FromStream(() => {
                
                 //...  // whatever you need to do to create your stream

           });
        }
    }

}