C# SaveFileDialog上的DialogResult.OK不工作

C# SaveFileDialog上的DialogResult.OK不工作,c#,wpf,dialog,savefiledialog,dialogresult,C#,Wpf,Dialog,Savefiledialog,Dialogresult,我试着,当我在SaveFileDialog中按save时,我会做一些事情。我正在努力修复,但总是出了问题 SaveFileDialog dlg2 = new SaveFileDialog(); dlg2.Filter = "xml | *.xml"; dlg2.DefaultExt = "xml"; dlg2.ShowDialog(); if (dlg2.ShowDialog() == DialogResult.OK) {....} 但是我在OK上有个错误,它说: 错误: “System.Nu

我试着,当我在
SaveFileDialog
中按save时,我会做一些事情。我正在努力修复,但总是出了问题

SaveFileDialog dlg2 = new SaveFileDialog();
dlg2.Filter = "xml | *.xml";
dlg2.DefaultExt = "xml";
dlg2.ShowDialog();
if (dlg2.ShowDialog() == DialogResult.OK)
{....}
但是我在OK上有个错误,它说:

错误: “System.Nullable”不包含“OK”的定义,并且找不到接受“System.Nullable”类型的第一个参数的扩展方法“OK”(是否缺少using指令或程序集引用?)

我尝试使用以下代码修复:

DialogResult result = dlg2.ShowDialog(); //here is error again
if (result == DialogResult.OK)
                {....}
现在出现错误,请说:
“System.Windows.Window.DialogResult”是一个“属性”,但像“类型”一样使用

我假设您指的是
WPF
而不是
Windows窗体
下面是使用
SaveFileDialog

//configure save file dialog box
Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
dlg.FileName = "Document"; //default file name
dlg.DefaultExt = ".xml"; //default file extension
dlg.Filter = "XML documents (.xml)|*.xml"; //filter files by extension

// Show save file dialog box
Nullable<bool> result = dlg.ShowDialog();

// Process save file dialog box results
if (result == true)
{
   // Save document
   string filename = dlg.FileName;
}

DialogResult
return
System.Windows.Forms.DialogResult
。所以你可以这样使用=>

DialogResult result = dlg2.ShowDialog(); 
if (result == System.Windows.Forms.DialogResult.OK)
                {....}

与其检查dlg2.ShowDialog()是否等于DialogResult.OK,不如检查它是否等于true

if (dlg2.ShowDialog() == true)
{....}

这是一个非常古老的话题,但我将为您提供解决方案。您要查找的对话框结果(针对savefiledialog)为。是或!取消,使其看起来像这样:

if (dlg2.ShowDialog() == DialogResult.Yes)


如果是WPF还是Winforms?请参阅。同一问题
if (dlg2.ShowDialog() == DialogResult.Yes)
if (dlg2.ShowDialog() != DialogResult.Cancel)