How to create Dynamic Openfiledialog to select image and bind it to image control in wpf


First take a WPF new project application

and design form as follows:

XAML Code:
<Window x:Class="DynamicFileUpLoad.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml&quot;
Title="MainWindow" Height="350" Width="525">
    <Grid>
        <GroupBox Header="OpenfileDialog" Height="287" HorizontalAlignment="Left" Margin="12,12,0,0" Name="groupBox1" VerticalAlignment="Top" Width="479" FontWeight="Bold" FontSize="15">
            <Grid>
                <Image Height="251" HorizontalAlignment="Left" Margin="6,6,2,2" Name="image1" Stretch="Fill" VerticalAlignment="Top" Width="249" />
                <Button Content="BrowseImage" Height="35" HorizontalAlignment="Left" Margin="304,97,0,0" Name="BtnBrowse" VerticalAlignment="Top" Width="121" Click="BtnBrowse_Click" />
            </Grid>
        </GroupBox>
    </Grid>
</Window>

NameSpace:
using Microsoft.Win32;

CodeBehind(Under ButtonClick Event):
private void BtnBrowse_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                OpenFileDialog opnfdl = new OpenFileDialog();
                opnfdl.InitialDirectory = "My Documents";
                opnfdl.Title = "SelectFile";
                opnfdl.DefaultExt = ".jpg";
                opnfdl.Filter = "All Image files|*.jpg";
                if (opnfdl.ShowDialog() == true)
                {
                    image1.Source = new BitmapImage(new Uri(opnfdl.FileName));
                }
            }
            catch (Exception errorMsg)
            {
                MessageBox.Show(errorMsg.Message);
            }
        }

You Can Get Output like this:

DownloadSampleCode

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s