我希望用户选择一个目录,我将生成的文件将保存在其中。我知道在WPF中,我应该使用Win32中的OpenFileDialog,但不幸的是,对话框需要选择文件-如果我只是单击确定而不选择一个,它就会保持打开。我可以通过让用户选择一个文件,然后剥离路径以找出它属于哪个目录来“hack”该功能,但这充其量是不直观的。有人见过这种情况吗?


当前回答

对于那些不想创建自定义对话框,但仍然喜欢100% WPF方式,不想使用单独的ddl,额外的依赖项或过时的api的人,我提出了一个非常简单的hack,使用另存为对话框。

不需要使用指令,你可以简单地复制粘贴下面的代码!

它应该仍然是非常友好的,大多数人都不会注意到。

这个想法来自于这样一个事实,我们可以改变对话框的标题,隐藏文件,并很容易地处理产生的文件名。

这是一个大黑客肯定,但也许它会做的工作只是为了你的使用…

在这个例子中,我有一个文本框对象来包含结果路径,但是如果你愿意,你可以删除相关的行,并使用一个返回值…

// Create a "Save As" dialog for selecting a directory (HACK)
var dialog = new Microsoft.Win32.SaveFileDialog();
dialog.InitialDirectory = textbox.Text; // Use current value for initial dir
dialog.Title = "Select a Directory"; // instead of default "Save As"
dialog.Filter = "Directory|*.this.directory"; // Prevents displaying files
dialog.FileName = "select"; // Filename will then be "select.this.directory"
if (dialog.ShowDialog() == true) {
    string path = dialog.FileName;
    // Remove fake filename from resulting path
    path = path.Replace("\\select.this.directory", "");
    path = path.Replace(".this.directory", "");
    // If user has changed the filename, create the new directory
    if (!System.IO.Directory.Exists(path)) {
        System.IO.Directory.CreateDirectory(path);
    }
    // Our final value is in path
    textbox.Text = path;
}

这个黑客唯一的问题是:

确认按钮仍然显示“保存”而不是“选择目录”,但在像我这样的情况下,我“保存”目录选择,所以它仍然有效…… 输入字段仍然显示“文件名”而不是“目录名”,但我们可以说目录是一种文件类型… 仍然有一个“另存为类型”下拉菜单,但它的值是“目录(*.this.directory)”,用户不能更改它为其他东西,对我来说…

大多数人不会注意到这些,尽管我肯定更喜欢使用官方的WPF方式,如果微软能把他们的头从他们的屁股里拿出来,但在他们这样做之前,这是我的临时修复。

其他回答

实现你想要的最好的方法是创建你自己的基于wpf的控件,或者使用别人做的控件 为什么?因为在WPF应用程序中使用winforms对话框会有明显的性能影响(出于某种原因) 我推荐这个项目 https://opendialog.codeplex.com/ 或Nuget:

PM> Install-Package OpenDialog

它是非常MVVM友好的,它没有包装winforms对话框

看来微软。Win32 . net库不支持选择文件夹(只支持文件),所以你在WPF中运气不好(截至2022年7月)。我觉得现在最好的选择是WPF的Ookii: https://github.com/ookii-dialogs/ookii-dialogs-wpf。它工作得很好,正如预期的那样,在WPF减去微软的支持。你可以把它作为NuGet包来获取。XAML视图背后的代码:

public partial class ExportRegionView : UserControl
{
    public ExportRegionView()
    {
        InitializeComponent();
    }
    private void SavePath(object sender, RoutedEventArgs e)
    {
        var dialog = new Ookii.Dialogs.Wpf.VistaFolderBrowserDialog();
        dialog.Description = "SIPAS Export Folder";
        dialog.UseDescriptionForTitle = true;
        if (dialog.ShowDialog().GetValueOrDefault())
        {
            ExportPath.Text = dialog.SelectedPath;
        }
    }
}

XAML: <Button Grid.Row="1" Grid.Column="3" Style="{DynamicResource Esri_Button}" Click="SavePath" Margin="5,5,5,5">Path</Button>

Ookii VistaFolderBrowserDialog就是你想要的。

如果你只想要Ooki对话框中的文件夹浏览器,然后下载源代码,为文件夹浏览器挑选你需要的文件(提示:7个文件),它可以在。net 4.5.2中构建。我必须给System.Drawing添加一个引用。将原项目中的参考资料与你的进行比较。

如何确定哪些文件?在不同的Visual Studio实例中打开你的应用程序和Ookii。将VistaFolderBrowserDialog.cs添加到应用程序中,并继续添加文件,直到构建错误消失。你在Ookii项目中找到依赖项-控制-单击你想要跟踪到它的源(双关语)。

如果你懒得这么做,这里有你需要的文件……

NativeMethods.cs
SafeHandles.cs
VistaFolderBrowserDialog.cs
\ Interop
   COMGuids.cs
   ErrorHelper.cs
   ShellComInterfaces.cs
   ShellWrapperDefinitions.cs

编辑VistaFolderBrowserDialog.cs中的第197行,除非你想包含它们的资源。Resx

抛出新的InvalidOperationException(Properties.Resources.FolderBrowserDialogNoRootFolder);

throw new InvalidOperationException("Unable to retrieve the root folder.");

根据他们的license.txt将他们的版权声明添加到你的应用中

在\Ookii.Dialogs.Wpf.Sample\MainWindow.xaml.cs第160-169行代码是一个例子,你可以使用,但你需要删除这个,从MessageBox。显示(这个,用于WPF。

在我的机器上工作

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Gearplay
{
    /// <summary>
    /// Логика взаимодействия для OpenFolderBrows.xaml
    /// </summary>
    public partial class OpenFolderBrows : Page
    {
        internal string SelectedFolderPath { get; set; }
        public OpenFolderBrows()
        {
            InitializeComponent();
            Selectedpath();
            InputLogicalPathCollection();
             
        }

        internal void Selectedpath()
        {
            Browser.Navigate(@"C:\");
            
            Browser.Navigated += Browser_Navigated;
        }

        private void Browser_Navigated(object sender, NavigationEventArgs e)
        {
            SelectedFolderPath = e.Uri.AbsolutePath.ToString();
            //MessageBox.Show(SelectedFolderPath);
        }

        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
          
           
        }
        
        string [] testing { get; set; }
        private void InputLogicalPathCollection()
        {            // add Menu items for Cotrol 
            string[] DirectoryCollection_Path = Environment.GetLogicalDrives(); // Get Local Drives
            testing = new string[DirectoryCollection_Path.Length];
            //MessageBox.Show(DirectoryCollection_Path[0].ToString());
            MenuItem[]  menuItems = new MenuItem[DirectoryCollection_Path.Length]; // Create Empty Collection
            for(int i=0;i<menuItems.Length;i++)
            {
                // Create collection depend how much logical drives 
                menuItems[i] = new MenuItem();
                menuItems[i].Header = DirectoryCollection_Path[i];
                menuItems[i].Name = DirectoryCollection_Path[i].Substring(0,DirectoryCollection_Path.Length-1);
                DirectoryCollection.Items.Add(menuItems[i]);
                menuItems[i].Click += OpenFolderBrows_Click;
                testing[i]= DirectoryCollection_Path[i].Substring(0, DirectoryCollection_Path.Length - 1);
            }

            

        }
        
        private void OpenFolderBrows_Click(object sender, RoutedEventArgs e)
        {

            foreach (string str in testing)
            {
                if (e.OriginalSource.ToString().Contains("Header:"+str)) // Navigate to Local drive
                {
                    Browser.Navigate(str + @":\");
                   
                }


            }


        }

        private void Goback_Click(object sender, RoutedEventArgs e)
        {// Go Back
            try
            {
                Browser.GoBack();
            }catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void Goforward_Click(object sender, RoutedEventArgs e)
        { //Go Forward
            try
            {
                Browser.GoForward();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private void FolderForSave_Click(object sender, RoutedEventArgs e)
        {
            // Separate Click For Go Back same As Close App With send string var to Main Window ( Main class etc.) 
            this.NavigationService.GoBack();
        }
    }
}

你可以像这样在WPF中使用smth。我已经创建了示例方法。 下面的检查。

public string getFolderPath()
{
           // Create OpenFileDialog 
           Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();

           OpenFileDialog openFileDialog = new OpenFileDialog();
           openFileDialog.Multiselect = false;

           openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
           if (openFileDialog.ShowDialog() == true)
           {
               System.IO.FileInfo fInfo = new System.IO.FileInfo(openFileDialog.FileName);
               return fInfo.DirectoryName;
           }
           return null;           
       }