vb.net自定义控件,如何使属性打开文件对话框以选择文件(将自定义控件放在窗体上之后)

问题描述 投票:0回答:1

我在Visual Studio中使用vb.net,并且具有一个自定义控件,该控件的属性包含目标计算机上存在的文件位置的名称(完整路径)。

确切的路径会根据目标PC的类型而有所不同,并且通常在我将自定义控件添加到表单后立即设置,而我仍处于项目的设计模式下,因此当我的应用程序运行时,它将拾取属性中的文件名。

如果该属性打开了一个文件对话框以让我浏览到该位置(类似于浏览图像和颜色属性时如何打开对话框),将很方便,但是在Visual Basic中这似乎是不可能的。

经过数天的搜索,我发现了几篇文章涉及其他编程语言的主题(请参见下面的示例片段,但我仍无法弄清楚如何使其在Visual Basic中起作用。

这里是我发现提到使用编辑器的摘要,这可能是入门的线索。

[Editor(typeof(FileSelectorTypeEditor), typeof(UITypeEditor))]
public string Filename
{
   get { return _filename; }
   set { _filename = value; }
}

希望外面的人可以以正确的方式带领我。

vb.net properties custom-controls design-time filedialog
1个回答
0
投票

FileSelectorTypeEditor可能是派生自FileNameEditorFolderNameEditor的自定义类。

您可以使用标准类来实现这两者,也可以使用您自己的类来扩展默认值,正如您在所找到的C#源代码中所看到的那样。

这里,我正在使用一个专门的FileNameEditor类,命名为(有些缺乏想象力)SpecializedFileNameEditor和将FolderNameEditor分配给该类的两个属性的标准UITypeEditor

SpecializedFileNameEditor使用OpenFileDialog,在该对话框中预选择了过滤器。►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.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
        Protected Overrides Sub InitializeDialog(ofd As OpenFileDialog)
            MyBase.InitializeDialog(ofd)
            ofd.RestoreDirectory = true
            ofd.Filter = "PNG Images (*.png)|*.png"
        End Sub
    End Class
End Class
© www.soinside.com 2019 - 2024. All rights reserved.