2013-02-14 128 views
2

當我點擊按鈕打開文件時,OpenFileDialog對話框打開兩次。第一個盒子只打開圖像文件和第二個盒子文本文件。如果用戶決定在不選擇文件的情況下關閉第一個框,第二個框也會彈出。我不確定我在這個問題上看到了什麼。任何幫助,將不勝感激。謝謝!c#/ WPF openFileDialog對話框打開兩次

OpenFileDialog of = new OpenFileDialog(); 
of.Filter = "All Image Formats|*.jpg;*.png;*.bmp;*.gif;*.ico;*.txt|JPG Image|*.jpg|BMP image|*.bmp|PNG image|*.png|GIF Image|*.gif|Icon|*.ico|Text File|*.txt"; 

if (of.ShowDialog() == System.Windows.Forms.DialogResult.OK) 
{ 
try 
{ 
    image1.Source = new BitmapImage(new Uri(of.FileName)); 

    // enable the buttons to function (previous page, next page, rotate left/right, zoom in/out) 
    button1.IsEnabled = false; 
    button2.IsEnabled = false; 
    button3.IsEnabled = false; 
    button4.IsEnabled = false; 
    button5.IsEnabled = true; 
    button6.IsEnabled = true; 
    button7.IsEnabled = true; 
    button8.IsEnabled = true;       
} 
catch (ArgumentException) 
{ 
    // Show messagebox when argument exception arises, when user tries to open corrupted file 
    System.Windows.Forms.MessageBox.Show("Invalid File"); 
} 
} 
else if(of.ShowDialog() == System.Windows.Forms.DialogResult.OK) 
{ 
try 
{ 
    using (StreamReader sr = new StreamReader(of.FileName)) 
    { 
     textBox2.Text = sr.ReadToEnd(); 
     button1.IsEnabled = true; 
     button2.IsEnabled = true; 
     button3.IsEnabled = true; 
     button4.IsEnabled = true; 
     button5.IsEnabled = true; 
     button6.IsEnabled = true; 
     button7.IsEnabled = true; 
     button8.IsEnabled = true; 

    } 
} 
catch (ArgumentException) 
{ 
    System.Windows.Forms.MessageBox.Show("Invalid File"); 
} 
} 
+0

這是因爲第一個if爲false,那麼它會計算第二個if語句。聽起來像這種方法做了幾件事,我會建議重構,並在單獨的方法中調用ShowDialogs()。 – timmy 2013-02-14 19:35:25

+0

我不知道你在做什麼......打開兩個對話框的目的是什麼?看起來好像您可以兩次選擇文本文件。 – 2013-02-14 19:35:51

+0

我編輯了你的標題。請參閱:「[應該在其標題中包含」標籤「](http://meta.stackexchange.com/questions/19190/)」,其中的共識是「不,他們不應該」。 – 2013-02-14 19:49:44

回答

5

你打電話ShowDialog()兩次:

if (of.ShowDialog() == System.Windows.Forms.DialogResult.OK) 
    { 
     //... 
    } 
    else if(of.ShowDialog() == System.Windows.Forms.DialogResult.OK) 

只需撥打一次,並保存結果:

var dialogResult = of.ShowDialog(); 
if (dialogResult == System.Windows.Forms.DialogResult.OK) 
{ 
     //... 
} 
// Note that the condition was the same! 
else if(dialogResult != System.Windows.Forms.DialogResult.OK) 

編輯:

如果你想第二個對話框只有在第一次處理時才顯示,你可以這樣做:

var dialogResult = of.ShowDialog(); 
if (dialogResult == System.Windows.Forms.DialogResult.OK) 
{ 
     //... 

    // Do second case here - Setup new options 
    dialogResult = of.ShowDialog(); //Handle text file here 
} 
+0

啊,謝謝你的幫忙! – user2029074 2013-02-14 19:35:51

+0

'if'和'else if'語句具有相同的條件。 – AbZy 2013-02-14 19:40:21

+0

@AbZy是啊 - 原來也是這樣...請注意 – 2013-02-14 19:44:57

1

要調用ShowDialog無論是在ifelse if條件。該方法負責顯示對話框,並且只有很好的副作用,告訴你用戶點擊了什麼。

將方法的結果存儲在變量中,並檢查if..elseif條件。