views:

39

answers:

2

Hi All

I'm a noob when it comes to WPF; In win forms I can do this:

public void blah()
{
   using( var o = new OpenFileDialog())
   {
        if(o.ShowDialog() == DialogResult.OK)
        {
             PictureBox p = new PictureBox();
             p.ImageLocation = o.FileName;
             p.AutoSize = SizeMode.AutoSize;
             this.Controls.Add(p);
        }
   }
}

But in WPF I have no idea at all and not even MSDN will give me any clear info on how to insert a pic onto the form at runtime! Can someone please help?

Thank you very much

+1  A: 

Basically you need to create a System.Windows.Controls.Image and set its Source to a System.Windows.Media.Imaging.BitmapImage. Then add the image to the Children of the Container. You may want to put the image inside of another container first like a Canvas. Here's a quick translation of your code, but you'll likely need to play with it a bit to get it just right.

public void blah()
{
   using( var o = new OpenFileDialog())
   {
        if(o.ShowDialog() == DialogResult.OK)
        {
             Image i = new Image();
             i.Source = new BitmapImage(o.FileName);
             //p.AutoSize = SizeMode.AutoSize; <= not sure about this part.
             this.Children.Add(i);
        }
   }
}
juharr
re your comment about the sizemode property, yeh my brain got dead for a little while and i forgot the proper way of changing size mode lol. Thanks for your answer :), will update my question to show correct sizemode code so people don't use the wrong version :)
lucifer
+1  A: 

You could use XAML and some bindings (and possibly a converter to convert a string to an image source). It's more in keeping with the WPF way of doing things.

Example without converter:

XAML

<Window
    ...
    x:Name="this"
    DataContext="{Binding ElementName=this}">
    <Grid>
        <ListView ItemsSource="{Binding MyImageCollection}">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <Image Source="{Binding}" />
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </Grid>
</Window>

Code Behind

public class Window1 : Window {
    public ObservableCollection<ImageSource> MyImageCollection { get; set; }
    ...
    public void blah()
    {
        using( var o = new OpenFileDialog())
        {
            if(o.ShowDialog() == DialogResult.OK)
            {
                MyImageCollection.Add(new BitmapImage(new Uri(o.FileName)));
            }
        }
    }
}
jeffora