在WPF使用FolderBrowserDial…

原来没有这东东
相信习惯以前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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值