Set image source to a URI

前端 未结 3 1374
臣服心动
臣服心动 2021-01-23 12:08

If i have a link to an image online and i want to set the image source to this uri, how should i do it best? The code i\'m trying is shown below.

3条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-23 12:29

    The way you are setting the image source in code-behind is absolutely fine. The other alternative, if you are using binding / MVVM is to convert your string URL to an image source using a converter:

    public class StringToImageConverter : IValueConverter
    {
    
      public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
      {
        string url = value as string;
        Uri uri = new Uri(url);
        return new BitmapImage(uri);
      }
    
      public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
      {
        throw new NotImplementedException();
      }
    }
    

提交回复
热议问题