在图像按钮中加载图像

时间:2015-07-23 05:47:09

标签: c# wpf image silverlight

我使用下面的代码在我的图片按钮中加载图片。但是Image没有加载Button。但是,我没有收到任何错误。

XAML代码:

Image  Name="imgPhoto" HorizontalAlignment="Left" Height="160" Margin="10,41,0,0" VerticalAlignment="Top" Width="164"/>

Button Content="Load" HorizontalAlignment="Left" Margin="191,67,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click_1"/>

以下是在图像按钮中加载图像的代码。

按钮单击事件代码:

  private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "Image files (*.jpg)|*.jpg|All Files (*.*)|*.*";
            if (dlg.ShowDialog() == true)
            {
               string selectedFileName = dlg.File.Name;
               imgPhoto.Source = new BitmapImage(new Uri(selectedFileName, UriKind.Relative));
            }
        }

3 个答案:

答案 0 :(得分:0)

问题在于:UriKind.Relative。 如果您从文件名构建URI,从系统的文件对话框中选择,则它是绝对URI:

myImage.Source = new BitmapImage(new Uri(fileDialog.FileName));

换句话说,您应该将完整路径(例如“c:\ folder \ filename.ext”)视为绝对URI。

答案 1 :(得分:0)

使用OpenFIleDialog我们没有 File.Name 我们只有 FileName 属性获取或设置包含在文件对话框中选择的文件名的字符串

检查以下代码

OpenFileDialog objOpenFileDialog = new OpenFileDialog();
objOpenFileDialog.Filter = "Image Files(.jpg)|*.jpg;*.gif;*.png";
 if (objOpenFileDialog.ShowDialog() == true)
            {
                imgPhoto.Source =new BitmapImage(new Uri(objOpenFileDialog.FileName));
            }  

答案 2 :(得分:0)

更改imgPhoto.Source代码如下

private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
        dlg.Filter = "Image files (*.jpg)|*.jpg|All Files (*.*)|*.*";
        if (dlg.ShowDialog() == true)
        {
            string selectedFileName = dlg.FileName;
            //imgPhoto.Source = new BitmapImage(new Uri(selectedFileName, UriKind.Relative));               
            imgPhoto.Source = (ImageSource)new ImageSourceConverter().ConvertFromString(selectedFileName);

        }
    }