将窗体制作为可重用控件(如FolderBrowser) [英] Making a Form as a reusable Control like FolderBrowser

查看:84
本文介绍了将窗体制作为可重用控件(如FolderBrowser)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个模拟 FolderBrowseDialog 的表单,但是添加了一些我想要的功能。它已经过测试并且可以正常运行,所以现在我想将其作为控件。
我的问题是,我从 UserControl 继承而不是从 Form 继承时, Close()方法,并且我不再有 FormClosing 事件。
当我单击确定或取消按钮时,如何关闭表单并将控件返回给调用对象?

I have created a form that emulates a FolderBrowseDialog, but with some added features I wanted. It's tested and working, so now I want to make it into a control. My problem is that as soon as I inherit from UserControl instead of Form, I no longer have a Close() method, and I no longer have a FormClosing event. When I click on the OK or Cancel button, how do I close the form and return control to the calling object?

推荐答案

要使其成为可重用的组件,而不是尝试从 Control 派生它,请创建一个 Component ,即使用该形式。这样,它可以显示在工具箱中,并且您可以像其他组件一样将组件的实例拖放到设计图面上。

To make it a reusable component, instead of trying to derive it from Control, create a Component which uses that form. This way it can show in toolbox and you can drop an instance of your component on design surface like other components.

您的组件应包含您要从对话框中公开的某些属性,还应包含创建的 ShowDialog 方法您的表单使用一些属性(例如标题,初始目录),并且将您的自定义表单显示为对话框并设置一些属性(例如选定的文件夹)并返回对话框结果。例如:

Your component should contain some properties which you want to expose from the dialog, also contain a ShowDialog method which created your form using some properties (like title, initial directory) and the shows your custom form as dialog and sets some properties (like selected folder) and returns the dialog result. For example:

using System.ComponentModel;
using System.Windows.Forms;
public partial class MyFolderBrowser : Component
{
    public string Text { get; set; }
    public string SelectcedFolder { get; set; }
    public DialogResult ShowDialog()
    {
        using (var f = new YourCustomForm() { Text = this.Text })
        {
            var result = f.ShowDialog();
            if (result == DialogResult.OK)
                SelectcedFolder = f.SelectedFolder;
            return result;
        }
    }
}

这篇关于将窗体制作为可重用控件(如FolderBrowser)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆