After searching far and wide, and getting nowhere, I decided to ask.
I have a .NET 5.0 WPF project I am working on, and I have to bind an URL (of an online image) to the source of an image on my form.
I have tried the following:
CoverImage.Source = new BitmapImage("https://somesite..com/img.png");
as well as binding it via XAML:
///XAML:
<Image Name="CoverImage"
Source="{Binding PreviewSource}"/>
///C#
public string PreviewSource { get; set; } = "https://somesite..com/img.png";
I have tried other solutions such as getting the image from a HrrpRequest and then creating it through a MemoryStream.
Using local images (that are on the pc) works without issues.
CodePudding user response:
new BitmapImage(new Uri("https://www.google.se/images/branding/googlelogo/2x/googlelogo_color_92x30dp.png"))`
and
<Image Name="CoverImage" Source="https://www.google.se/images/branding/googlelogo/2x/googlelogo_color_92x30dp.png"/>
...works just as expected on .NET 5.
Make sure that your URL is valid and reachable from your client machine.
CodePudding user response:
Are you sure the datacontext is correct? It works for me in the app below.
Xaml Code
<Grid>
<Image Name="CoverImage" Source="{Binding ImageSource}"/>
</Grid>
ViewModel
class MainWindowViewModel : ViewModelBase
{
private BitmapImage _imageSource;
public BitmapImage ImageSource
{
get => _imageSource;
set => SetProperty(ref _imageSource, value);
}
public MainWindowViewModel()
{
ImageSource = new BitmapImage(new Uri("https://www.google.se/images/branding/googlelogo/2x/googlelogo_color_92x30dp.png"));
}
}
ViewModelBase
public abstract class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual bool SetProperty<T>(ref T member, T value, [CallerMemberName] string propertyName = null)
{
if (EqualityComparer<T>.Default.Equals(member, value))
{
return false;
}
member = value;
OnPropertyChanged(propertyName);
return true;
}
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
=> PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
MainWindow.xaml.cs
public MainWindow()
{
DataContext = new MainWindowViewModel();
InitializeComponent();
}