最近论坛中有用户询问 C1FilePicker 如何在 OpenFileDialog 中显示绝对路径。默认情况下,OpenFileDialog对话框仅仅显示选择文件的名称。
实现方法比较简单,本篇文章对 WPF 控件的初学者会有所帮助。这个功能可以通过继承 C1FilePicker 和抓取 “浏览按钮”点击事件来实现。在浏览按钮点击事件中来自定义显示字符串。
C# Code
1: public class MyC1FilePicker : C1.WPF.C1FilePicker
2: {
3: public override void OnApplyTemplate()
4: {
5: base.OnApplyTemplate();
6:
7: var btn = GetTemplateChild("Browse") as Button;
8: btn.PreviewMouseDown +=
new MouseButtonEventHandler(btn_PreviewMouseDown);
9: }
10:
11: void btn_PreviewMouseDown(object sender, MouseButtonEventArgs e)
12: {
13: e.Handled = true;
14: OpenFileDialog opd = new OpenFileDialog();
15: opd.Filter = this.Filter;
16: opd.FileName = this.SelectedFile.ToString();
17: opd.InitialDirectory = this.SelectedFile.DirectoryName;
18: if (opd.ShowDialog() == true)
19: this.SelectedFile = new System.IO.FileInfo(opd.FileName);
20: }
21: }
XML Code
1: xmlns:local="clr-namespace:WPF_FilePicker_CustomOpenFile"
1: <local:MyC1FilePicker x:Name="c1FilePicker1" Width="125" Height="25"
Filter="Image Files(*.PNG;*.JPG;*.GIF)|*
.PNG;*.JPG;*.GIF|All files (*.*)|*.*"/>
Demo 下载:VS 2010 + C# + 。NET 4.0+Studio for WPF