在 AvaloniaUI 中,如何显示来自网络的图像 URL?

In AvaloniaUI, how to display an image from a web URL?

我正在使用 ReactiveUI 和 MVVM 开发 Avalonia 应用程序。 我想显示来自网络 URL 的图像,实现此目的的最佳行动方案是什么? 我设置了以下绑定:

                this.OneWayBind(
                    ViewModel,
                    vm => vm.UserProfileImageUrl,
                    v => v.ProfileImage.Source,
                    ImageConverter
                ).DisposeWith(disposables);

和绑定适配器:

        private IImage ImageConverter(string arg)
        {
        
        }

但我不知道如何实现绑定适配器来下载图像而不阻塞 UI。 Android 上是否有像 Glide 这样的工具?

提前谢谢你,

您可以异步下载图像并将其存储在您的 ViewModel 中,或者使用下载完成事件,例如:

public class MainWindowViewModel : ViewModelBase
    {
        private string chessboardUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/d/d5/Chess_Board.svg/2000px-Chess_Board.svg.png";
        public string ChessboardUrl
        {
            get => chessboardUrl;
            set {
                this.RaiseAndSetIfChanged(ref chessboardUrl, value);
                DownloadImage(ChessboardUrl);
                System.Diagnostics.Debug.WriteLine(ChessboardUrl);
            }
        }

        private Avalonia.Media.Imaging.Bitmap chessboard = null;
        public Avalonia.Media.Imaging.Bitmap Chessboard
        {
            get => chessboard;
            set => this.RaiseAndSetIfChanged(ref chessboard, value);
        }

        public MainWindowViewModel()
        {
            DownloadImage(ChessboardUrl);
        }

        public void DownloadImage(string url)
        {
            using (WebClient client = new WebClient())
            {
                client.DownloadDataAsync(new Uri(url));
                client.DownloadDataCompleted += DownloadComplete;
            }
        }

        private void DownloadComplete(object sender, DownloadDataCompletedEventArgs e)
        {
            try
            {
                byte[] bytes = e.Result;

                Stream stream = new MemoryStream(bytes);

                var image = new Avalonia.Media.Imaging.Bitmap(stream);
                Chessboard = image;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex);
                Chessboard = null; // Could not download...
            }
            
        }
    }

然后您可以轻松地绑定到 Url 和关联的图像。例如来自 XAML(具有适当的 DataContext):

<StackPanel>
    <Image Source="{Binding Chessboard}"
           Width="200"
           Height="200"
           Name="MyImage"></Image>
    <TextBox Text="{Binding ChessboardUrl}"></TextBox>
    
</StackPanel>