简体   繁体   English

在图像按钮中加载图像

[英]Load images in Image Button

I am using below code to load image in my image button. 我正在使用下面的代码在我的图像按钮中加载图像。 But the Image is not loading in Button. 但是图像未在Button中加载。 However, I'm not receiving any kind of error. 但是,我没有收到任何错误。

XAML Code: 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"/>

Below is the code to load the Image in Image Button. 以下是在“图像”按钮中加载图像的代码。

Button Click Event Code: 按钮单击事件代码:

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

The problem is here: UriKind.Relative . 问题在这里: UriKind.Relative If you're building URI from file name, picked up from system's file dialog, then it is absolute URI: 如果要从文件名构建URI,并从系统的文件对话框中选取,则它是绝对URI:

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

In other words, you should treat full path (eg, "c:\\folder\\filename.ext") as absolute URI. 换句话说,您应该将完整路径(例如,“ c:\\ folder \\ filename.ext”)视为绝对URI。

with OpenFIleDialog we don't have File.Name we have only FileName property which Gets or sets a string containing the file name selected in the file dialog box. 使用OpenFIleDialog,我们没有File.Name ,只有FileName属性,该属性获取或设置一个字符串,其中包含在文件对话框中选择的文件名。

check the below code 检查以下代码

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

Change imgPhoto.Source code as below 更改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);

        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM