programing

WPF에서 [Save As]대화상자를 표시하려면 어떻게 해야 하나요?

iphone6s 2023. 4. 17. 21:32
반응형

WPF에서 [Save As]대화상자를 표시하려면 어떻게 해야 하나요?

WPF/C#에서는 버튼을 클릭하여 데이터를 수집한 후 사용자가 머신에 다운로드할 수 있는 텍스트파일에 넣어야 합니다.처음 절반을 가져올 수 있지만, 사용자에게 "다른 이름으로 저장" 대화 상자를 표시하려면 어떻게 해야 합니까?파일 자체는 단순한 텍스트 파일입니다.

지금까지 두 답변 모두 Silverlight와 연결되어 있습니다.SaveFileDialog클래스: WPF 배리언트는 상당히 다른 네임스페이스입니다.

Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
dlg.FileName = "Document"; // Default file name
dlg.DefaultExt = ".text"; // Default file extension
dlg.Filter = "Text documents (.txt)|*.txt"; // 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;
}

Save File Dialog는 Microsoft에 있습니다.Win32 네임스페이스 - 이 문제를 해결하는 데 10분이 걸릴 수 있습니다.

다음은 샘플 코드입니다.

string fileText = "Your output text";

SaveFileDialog dialog = new SaveFileDialog()
{
    Filter = "Text Files(*.txt)|*.txt|All(*.*)|*"
};

if (dialog.ShowDialog() == true)
{
     File.WriteAllText(dialog.FileName, fileText);
}

클래스를 사용합니다.

Save FileDialog를 만들고 ShowDialog 메서드를 호출하기만 하면 됩니다.

지금까지의 예에서는 모두 Win32 네임스페이스를 사용하고 있습니다만, 다른 방법이 있습니다.

FileInfo file = new FileInfo("image.jpg");
var dialog = new System.Windows.Forms.SaveFileDialog();
dialog.FileName = file.Name;
dialog.DefaultExt = file.Extension;
dialog.Filter = string.Format("{0} images ({1})|*{1}|All files (*.*)|*.*",
    file.Extension.Substring(1).Capitalize(),
    file.Extension);
dialog.InitialDirectory = file.DirectoryName;

System.Windows.Forms.DialogResult result = dialog.ShowDialog(this.GetIWin32Window());
if (result == System.Windows.Forms.DialogResult.OK)
{

}

확장 방법을 사용하여 이 정보를 얻으려고 합니다.IWin32Window시각 제어 장치:

#region Get Win32 Handle from control
public static System.Windows.Forms.IWin32Window GetIWin32Window(this System.Windows.Media.Visual visual)
{
    var source = System.Windows.PresentationSource.FromVisual(visual) as System.Windows.Interop.HwndSource;
    System.Windows.Forms.IWin32Window win = new OldWindow(source.Handle);
    return win;
}

private class OldWindow : System.Windows.Forms.IWin32Window
{
    private readonly System.IntPtr _handle;
    public OldWindow(System.IntPtr handle)
    {
        _handle = handle;
    }

    System.IntPtr System.Windows.Forms.IWin32Window.Handle
    {
        get { return _handle; }
    }
}
#endregion

Capitalize()는 확장 방식이기도 하지만 문자열의 첫 글자를 대문자로 표시하는 예는 많이 있기 때문에 언급할 필요가 없습니다.

언급URL : https://stackoverflow.com/questions/5622854/how-do-i-show-a-save-as-dialog-in-wpf

반응형