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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10315188/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 13:19:07  来源:igfitidea点击:

Open file dialog and select a file using WPF controls and C#

c#wpftextboxopenfiledialog

提问by NoobMaster69

I have a TextBoxnamed textbox1and a Buttonnamed button1. When I click on button1I want to browse my files to search only for image files (type jpg, png, bmp...). And when I select an image file and click Ok in the file dialog I want the file directory to be written in the textbox1.textlike this:

我有一个TextBoxnamedtextbox1和一个Buttonnamed button1。当我单击时,button1我想浏览我的文件以仅搜索图像文件(类型 jpg、png、bmp...)。当我选择一个图像文件并在文件对话框中单击“确定”时,我希望将文件目录写入textbox1.text如下:

textbox1.Text = "C:\myfolder\myimage.jpg"

采纳答案by Klaus78

Something like that should be what you need

这样的东西应该是你需要的

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

回答by Dave

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;