2

当我单击按钮打开文件时,该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");
}
} 
4

2 回答 2

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

您在and条件下ShowDialog都在调用。该方法负责显示对话框,并且只有告诉您用户单击了什么的好副作用。ifelse if

将方法的结果存储在一个变量中,然后在 if..elseif 条件中检查它。

于 2013-02-14T19:33:43.003 回答