当我单击按钮打开文件时,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 :(得分: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
}
答案 1 :(得分:1)
您正在ShowDialog
和if
条件中调用else if
。该方法负责显示对话框,并且只有很好的副作用,也告诉您用户点击了什么。
将方法的结果存储在变量中,并在if..elseif条件中检查它。