随笔 - 61  文章 - 10  评论 - 370 

相信习惯以前winform开发的朋友们都对FolderBrowserDialog和OpenFileDialog这两个东东不陌生,但是在我最近做的WPF项目中

才发现这两个东东在WPF中却不是默认存在的,郁闷,好歹WPF也出来几年了,咋个微软的同志不与时俱进呢。

好了,说说具体怎么用吧。

OpenFileDialog

用这个东东需要引用Microsoft.Win32类库。还是老玩意可靠。

Microsoft.Win32.OpenFileDialog op = new Microsoft.Win32.OpenFileDialog();
         op.InitialDirectory = @"c:\";
          op.RestoreDirectory = true;
          op.Filter = "文本文件(*.txt)|*.txt|所有文件(*.*)|*.*";
          op.ShowDialog();
          txtPath.Text = op.FileName;

 

FolderBrowserDialog

这个要麻烦点点,先建一个类,比如命名为OldWindow.cs

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

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

 

然后在你要使用的地方这样写

System.Windows.Forms.FolderBrowserDialog dlg = new System.Windows.Forms.FolderBrowserDialog();
         System.Windows.Interop.HwndSource source = PresentationSource.FromVisual(this) as System.Windows.Interop.HwndSource;
         System.Windows.Forms.IWin32Window win = new {上面那个类所在的命名空间名称}.OldWindow(source.Handle);
         System.Windows.Forms.DialogResult result = dlg.ShowDialog(win);

         txtPath.Text = dlg.SelectedPath;

BTW:需要在项目中引用System.Windows.Forms.dll

 

无标题

posted on 2010-11-19 17:40 杨丹 阅读(844) 评论(3) 编辑 收藏

 回复 引用 查看   
#1楼 2010-11-19 23:31 | heywap      
不说不知道,一说吓一跳。
我正在学wpf桌面应用。看到你这篇文章,更觉得wpf还是相当的不成熟。这么基本的控件,居然还要调用winform的控件。真是wpf的悲哀.

 回复 引用 查看   
#2楼 2010-11-19 23:33 | heywap      
想想还真生气。ms全世界把wpf吹得像什么一样。
 回复 引用 查看   
#3楼 2010-11-20 00:58 | 南柯之石      
@heywap
不就FileBrowserDialog没有么,有什么奇怪的。那东西本来就不是WPF做的,而且也不应该用WPF做。