在WPF使用FolderBrowserDial…

来源:互联网 发布:sql删除重复字段 编辑:程序博客网 时间:2024/06/05 11:00
原来没有这东东
原文地址:在WPF使用FolderBrowserDialog和OpenFileDialog作者:Mars
相信习惯以前winform开发的朋友们都对FolderBrowserDialog和OpenFileDialog这两个东东不陌生,但是在我最近做的WPF项目中
才发现这两个东东在WPF中却不是默认存在的,郁闷,好歹WPF也出来几年了,咋个微软的同志不与时俱进呢。
好了,说说具体怎么用吧。

OpenFileDialog:
用这个东东需要引用Microsoft.Win32类库。还是老玩意可靠。
Microsoft.Win32.OpenFileDialog op = newMicrosoft.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
     IntPtrSystem.Windows.Forms.IWin32Window.Handle
     {
         get {return _handle; }
     }
     #endregion
  
 
然后在你要使用的地方这样写
System.Windows.Forms.FolderBrowserDialog dlg = newSystem.Windows.Forms.FolderBrowserDialog();
       System.Windows.Interop.HwndSource source =PresentationSource.FromVisual(this) asSystem.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
0 0
原创粉丝点击