WPF是否有本机文件对话框?

Seb*_*ray 48 c# wpf filedialog

System.Windows.Controls,我可以看到一个PrintDialog 然而,我似乎无法找到一个本地人FileDialog.我是否需要创建引用System.Windows.Forms或是否有其他方法?

Nol*_*rin 62

WPF确实具有内置(尽管不是本机)文件对话框.具体来说,它们处于略微意外的Microsoft.Win32命名空间(尽管仍然是WPF的一部分).特别参见OpenFileDialogSaveFileDialog类.

但请注意,这些类只是围绕Win32功能的包装,正如父命名空间所暗示的那样.但它确实意味着您不需要执行任何WinForms或Win32互操作,这使得它使用起来更好.不幸的是,对话框在"旧的"Windows主题中默认为样式,你需要一个小的黑客app.manifest来迫使它使用新的.

  • 您是否介意详细说明需要使用清单做什么才能获得新的Windows主题版本? (3认同)
  • @Sebastian:当然 - 这篇博文详细介绍:http://www.nbdtech.com/blog/archive/2008/06/16/The-Application-Manifest-Needed-for-XP-and-Vista-Style- File.aspx. (2认同)

Gre*_*vec 15

您可以创建一个简单的附加属性,以将此功能添加到TextBox.打开文件对话框可以像这样使用:

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="Auto"/>
    </Grid.ColumnDefinitions>
    <TextBox i:OpenFileDialogEx.Filter="Excel documents (.xls)|*.xls" Grid.Column="0" />
    <Button Grid.Column="1">Browse</Button>
</Grid>
Run Code Online (Sandbox Code Playgroud)

OpenFileDialogEx的代码:

public class OpenFileDialogEx
{
    public static readonly DependencyProperty FilterProperty =
      DependencyProperty.RegisterAttached("Filter",
        typeof (string),
        typeof (OpenFileDialogEx),
        new PropertyMetadata("All documents (.*)|*.*", (d, e) => AttachFileDialog((TextBox) d, e)));

    public static string GetFilter(UIElement element)
    {
      return (string)element.GetValue(FilterProperty);
    }

    public static void SetFilter(UIElement element, string value)
    {
      element.SetValue(FilterProperty, value);
    }

    private static void AttachFileDialog(TextBox textBox, DependencyPropertyChangedEventArgs args)
    {                  
      var parent = (Panel) textBox.Parent;

      parent.Loaded += delegate {

        var button = (Button) parent.Children.Cast<object>().FirstOrDefault(x => x is Button);

        var filter = (string) args.NewValue;

        button.Click += (s, e) => {
          var dlg = new OpenFileDialog();
          dlg.Filter = filter;

          var result = dlg.ShowDialog();

          if (result == true)
          {
            textBox.Text = dlg.FileName;
          }

        };
      };
    }
}
Run Code Online (Sandbox Code Playgroud)