Does WPF have a native file dialog?

前端 未结 4 625
迷失自我
迷失自我 2020-12-23 16:09

Under System.Windows.Controls, I can see a PrintDialog However, I can\'t seem to find a native FileDialog. Do I need to create a refe

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-23 16:46

    Thanks to Gregor S for a neat solution.

    In Visual Studio 2010 it seems to crash the designer however - so I've tweaked the code in the OpenFileDialogEx class. The XAML code stays the same:

    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 textBoxParent = textBox.Parent as Panel;
            if (textBoxParent == null)
            {
                Debug.Print("Failed to attach File Dialog Launching Button Click Handler to Textbox parent panel!");
                return;
            }
    
    
            textBoxParent.Loaded += delegate
            {
                var button = textBoxParent.Children.Cast().FirstOrDefault(x => x is Button) as Button;
                if (button == null)
                    return;
    
                var filter = (string)args.NewValue;
    
                button.Click += (s, e) =>
                {
                    var dlg = new OpenFileDialog { Filter = filter };
    
                    var result = dlg.ShowDialog();
    
                    if (result == true)
                    {
                        textBox.Text = dlg.FileName;
                    }
                };
            };
        }
    }
    
        

    提交回复
    热议问题