打开文件对话框并使用WPF控件和C#选择文件

Noo*_*r69 177 c# wpf textbox openfiledialog

我有一个TextBox名字textbox1和一个Button名字button1.当我点击button1我想浏览我的文件只搜索图像文件(类型jpg,png,bmp ...).当我选择一个图像文件并在文件对话框中单击"确定"时,我希望文件目录的写入方式textbox1.text如下:

textbox1.Text = "C:\myfolder\myimage.jpg"
Run Code Online (Sandbox Code Playgroud)

Kla*_*s78 412

这样的事情应该是你需要的

private void button1_Click(object sender, RoutedEventArgs e)
{
    // Create OpenFileDialog 
    Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();



    // Set filter for file extension and default file extension 
    dlg.DefaultExt = ".png";
    dlg.Filter = "JPEG Files (*.jpeg)|*.jpeg|PNG Files (*.png)|*.png|JPG Files (*.jpg)|*.jpg|GIF Files (*.gif)|*.gif"; 


    // Display OpenFileDialog by calling ShowDialog method 
    Nullable<bool> result = dlg.ShowDialog();


    // Get the selected file name and display in a TextBox 
    if (result == true)
    {
        // Open document 
        string filename = dlg.FileName;
        textBox1.Text = filename;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • if(result.HasValue && result.Value)而不是if(result == true) (15认同)
  • @eflles样本在技术上是正确的.来自http://msdn.microsoft.com/en-us/library/2cf62fcy.aspx:*当您对可空类型进行比较时,如果其中一个可空类型的值为null而另一个不是,则所有比较都会进行评估错误除了!=(不等于).*但是我想可以说这是否是对这种技术性的利用(我个人认为在这种情况下可行). (5认同)
  • @efles你在http://msdn.microsoft.com/en-us/library/microsoft.win32.openfiledialog.aspx的官方示例代码中提供的价值是多少? (2认同)

Dav*_*ave 23

var ofd = new Microsoft.Win32.OpenFileDialog() {Filter = "JPEG Files (*.jpeg)|*.jpeg|PNG Files (*.png)|*.png|JPG Files (*.jpg)|*.jpg|GIF Files (*.gif)|*.gif"}; 
var result = ofd.ShowDialog();
if (result == false) return;
textBox1.Text = ofd.FileName;
Run Code Online (Sandbox Code Playgroud)