【问题标题】:Open file dialog and select a file using WPF controls and C#打开文件对话框并使用 WPF 控件和 C# 选择文件
【发布时间】:2012-05-06 02:37:47
【问题描述】:

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

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

【问题讨论】:

    标签: c# wpf textbox openfiledialog


    【解决方案1】:

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

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

    【讨论】:

    • if (result.HasValue && result.Value) 而不是 if (result == true)
    • @efles 与msdn.microsoft.com/en-us/library/… 的官方示例代码相比,您的方式提供的价值是多少?
    • @eflles 该示例在技术上是正确的。来自msdn.microsoft.com/en-us/library/2cf62fcy.aspx当您对可空类型执行比较时,如果一个可空类型的值为 null 而另一个不是,则所有比较的结果都为 false,除了 !=(不等于)。 但是我认为这是否是对这种技术性的利用可能会引起争论(我个人认为在这种情况下是可以的)。
    【解决方案2】:
    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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-25
      • 2011-04-29
      • 2012-03-02
      • 2011-04-25
      • 2012-08-19
      • 1970-01-01
      相关资源
      最近更新 更多