2012-04-25 116 views
135

我有一個名爲textbox1TextBox和一個名爲button1Button。 當我點擊button1我想瀏覽我的文件以僅搜索圖像文件(類型jpg,png,bmp ...)。 當我選擇一個圖像文件,並在文件對話框我希望被寫入的文件目錄中的textbox1.text這樣單擊確定:打開文件對話框並使用WPF控件和C#選擇文件

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

回答

333

類似的東西應該是你所需要的

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

if(result.HasValue && result.Value)而不是if(result == true) – eflles 2014-04-26 10:33:09

+2

@efles您的方式提供的值超過http://msdn.microsoft.com/zh-cn/上的官方示例代碼, us/library/microsoft.win32.openfiledialog.aspx? – 2014-04-30 18:09:27

+3

@eflles樣本在技術上是正確的。從http://msdn.microsoft.com/en-us/library/2cf62fcy.aspx:*執行與可空類型的比較時,如果其中一個可空類型的值爲空而另一個不爲空,則所有比較都會評估除了!=(不等於)之外,我的觀點是錯誤的。*但是,我認爲可以認爲這是否是對這一技術性的利用(我個人認爲在這種情況下是可以的)。 – 2014-07-01 22:00:00

16
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; 
相關問題