【问题标题】:Load images in Image Button在图像按钮中加载图像
【发布时间】:2015-10-13 06:29:22
【问题描述】:

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

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));
            }
        }

【问题讨论】:

    标签: c# wpf image silverlight


    【解决方案1】:

    对于 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】:

      问题在这里:UriKind.Relative。 如果您从文件名构建 URI,从系统的文件对话框中获取,那么它是绝对 URI:

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

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

      【讨论】:

        【解决方案3】:

        修改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);
        
                }
            }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-01-18
          • 2011-11-24
          • 1970-01-01
          • 2016-04-13
          • 2016-12-01
          相关资源
          最近更新 更多