我有一个自定义控件,该控件的属性保存目标计算机上存在的文件位置的名称(完整路径)。
确切的路径会根据目标PC的类型而有所不同,并且通常在我将自定义控件添加到Form后立即设置,而我仍处于项目的设计模式,因此当我的应用程序运行时,它会选择属性中的文件名。
如果该属性打开了一个文件对话框以让我浏览到该位置(类似于浏览图像和颜色属性时如何打开对话框),将很方便,但是在Visual Basic中这似乎是不可能的。
经过数天的搜索,我发现了几篇文章涉及其他编程语言的主题(请参见下面的示例片段,但我仍无法弄清楚如何使其在Visual Basic中起作用。
这里是我发现提到使用编辑器的摘要,这可能是入门的线索。
[Editor(typeof(FileSelectorTypeEditor), typeof(UITypeEditor))]
public string Filename
{
get { return _filename; }
set { _filename = value; }
}
希望外面的人可以以正确的方式带领我。
FileSelectorTypeEditor
可能是派生自FileNameEditor或FolderNameEditor的自定义类。
您可以使用标准类来实现这两者,也可以使用您自己的类来扩展默认值,正如您在所找到的C#源代码中所看到的那样。
这里,我正在使用一个专门的FileNameEditor
类,命名为(有些缺乏想象力)SpecializedFileNameEditor
和将FolderNameEditor
分配给该类的两个属性的标准UITypeEditor
。
►ImagePath
属性编辑器是SpecializedFileNameEditor
对象,它使用OpenFileDialog,在其中预选择了过滤器。►ImageFolder
属性编辑器是标准的FolderNameEditor
,它将打开FolderBrowserDialog。
我还附加了ExpandableObjectConverter类型转换器,因此您可以在PropertyGrid中将这两个属性显示为可扩展属性选择器。
您可以在此处查看示例:How to bind child Controls of a User Control to a Public Property
Imports System.ComponentModel
Imports System.Drawing.Design
Imports System.IO
Imports System.Windows.Forms
Imports System.Windows.Forms.Design
<TypeConverter(GetType(ExpandableObjectConverter))>
Public Class ImagePickerClass
Public Sub New()
' Initialize [...]
End Sub
<Editor(GetType(SpecializedFileNameEditor), GetType(UITypeEditor))>
Public Property ImagePath As String
<Editor(GetType(FolderNameEditor), GetType(UITypeEditor))>
Public Property ImageFolder As String
Public Class SpecializedFileNameEditor
Inherits FileNameEditor
Private currentValue As String = String.Empty
Public Overrides Function EditValue(context As ITypeDescriptorContext, provider As IServiceProvider, value As Object) As Object
currentValue = value.ToString()
Return MyBase.EditValue(context, provider, value)
End Function
Protected Overrides Sub InitializeDialog(ofd As OpenFileDialog)
MyBase.InitializeDialog(ofd)
If Not currentValue.Equals(String.Empty) Then
ofd.InitialDirectory = Path.GetDirectoryName(currentValue)
End If
ofd.Filter = "PNG Images (*.png)|*.png"
End Sub
End Class
End Class