Search code examples
c#wpf

Loading image from the web at runtime in WPF


I'm trying to load an image from an url in WPF in a very simple way, but it's not working. Any help ? The code is below :

Main XAML

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication1"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="279*"></RowDefinition>
            <RowDefinition Height="41*">                
            </RowDefinition>
        </Grid.RowDefinitions>
        <Image x:Name="image1" Grid.Row="0"></Image>
        <TextBox Grid.Row="1" Margin="0,0,10,0"></TextBox>

    </Grid>
</Window>

Code-behind

 public partial class MainWindow : Window
    {
        public MainWindow()
        {

            InitializeComponent();

            var bi = new BitmapImage();
            bi.BeginInit();
            bi.UriSource = new Uri("http://www.clipartkid.com/images/817/pic-of-german-flag-clipart-best-VkuN37-clipart.jpeg");
            bi.EndInit();

            //var img = new Image();
            image1.Source = bi;
        }
    }

Solution

  • Funny indeed! Works alright at my other laptop now. Must be something with the firewall settings. And yeps, I've made things even simpler now. Binding the source of the image in XAML to just a string property I've set in a ViewModel class.

    <Image x:Name="image1" Source ="{Binding MyPic}" Grid.Row="0"></Image>
    

    class MyViewModel
        {
            public string MyPic {
                get { return @"http://www.clipartkid.com/images/817/pic-of-german-flag-clipart-best-VkuN37-clipart.jpeg"; }
            }
        }
    

    Thanks for the responses, and sorry for the confusion.

    -Ron