c# - 如何在 xamarin 表单(android)上显示共享文件夹中的图像?
问题描述
我在 xamarin 表单上显示图像时遇到问题。图像存储在我们网络上的共享文件夹中。我正在使用 Sharpcifs。
这是相关视图模型的代码:
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());
}
我用泛型替换了域、用户名和密码。我确实使用了正确的域名、用户名和密码。在 xaml 中:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Class="Picking.Views.ProductPositionsPage"
Title="{Binding Title}">
<ContentPage.Content>
<Grid RowSpacing="0">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="70"/>
</Grid.RowDefinitions>
<Image Grid.Row="0" Source="{Binding ProductImage}"/>
</Grid>
</ContentPage.Content>
</ContentPage>
解决方案
如果你想在运行时设置图像的来源,不要忘记 在你的 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
});
}
}
}