2

ボタンをクリックしてファイルを開くと、OpenFileDialogボックスが2回開きます。最初のボックスは画像ファイルと2番目のボックスのテキストファイルのみを開きます。ユーザーがファイルを選択せず​​に最初のボックスを閉じることにした場合、2番目のボックスもポップアップします。この問題について何を見ているのかわかりません。どんな助けでもいただければ幸いです。ありがとう!

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");
}
} 
4

2 に答える 2

5

あなたはShowDialog()2回電話しています:

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)

編集:

最初のダイアログが処理されたときにのみ2番目のダイアログを表示する場合は、次のようにします。

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
}
于 2013-02-14T19:33:50.007 に答える
1

と条件ShowDialogの両方で呼び出しています。このメソッドはダイアログの表示を担当し、ユーザーが何をクリックしたかを通知するという優れた副作用しかありません。ifelse if

メソッドの結果を変数に格納し、代わりにif..elseif条件でそれを確認します。

于 2013-02-14T19:33:43.003 に答える